Python Variable keeps resetting using actions.py - python-3.x

I guys. I have made an actions.py file with several classes. What Im trying to do is that I want a variable (in this case its called flag) I want to set it at zero as default and change it through the function. For some reason it keeps resetting flag to 0 when flag is used in another function.
`
from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
# Import the getData module to fetch the data.
from dbConnect import getData
import dbConnect
import mysql.connector
flag = 0
class FindByLocation(Action):
def name(self) -> Text:
return "action_find_by_location"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
location = tracker.get_slot("location")
price= tracker.get_slot("price")
cuisine = tracker.get_slot("cuisine")
print(location)
# write the sql query here.
query = "SELECT Name FROM Restaurant WHERE Location = '%s'" % location
query3 = "SELECT COUNT(Name) FROM Restaurant WHERE Location = '%s' LIMIT 5" % location
query2 = "CREATE VIEW LocationView AS SELECT RestaurantID, Name, PhoneNumber, Rating, PriceRange, Location, Sublocation FROM Restaurant WHERE Sublocation = '%s'"%(location)
#pass the sql query to the getData method and store the results in `data` variable.
var_location = getData(query)
print(var_location)
if not var_location:
flag = 1
var_sublocation = getData(query2)
dispatcher.utter_message(text="یہ جگہ کس ایریا میں ہے")
else:
if cuisine is not None:
count = getData(query3)
dispatcher.utter_message(text="Find By Location",json_message=var_location)
dispatcher.utter_message(text="Results found",json_message=count)
dispatcher.utter_message(text="آپ کس پرائس میں کھانا پسند کریں گے")
else:
count = getData(query3)
dispatcher.utter_message(text="Find By Location",json_message=var_location)
dispatcher.utter_message(text="Results found",json_message=count)
dispatcher.utter_message(text="آپ کس طرح کا کھانا پسند کریں گے؟")
return[]
class FindBySublocation(Action):
def name(self) -> Text:
return "action_find_by_sublocation"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
flag = 1
print("FLAG VALUEEEEEE")
print(flag)
location = tracker.get_slot("location")
query = "SELECT Name, Rating FROM LocationView WHERE Location = '%s'" % (location)
query2 = "SELECT COUNT(Name), Rating FROM LocationView WHERE Location = '%s'" % (location)
location = getData(query)
location_count = getData(query2)
dispatcher.utter_message(text="Sublocation Restaurants Found",json_message=location)
dispatcher.utter_message(text="Results found",json_message=location_count)
dispatcher.utter_message(text="آپ کس طرح کا کھانا پسند کریں گے؟")
return[]
class FindByCuisineAndLocation(Action):
def name(self) -> Text:
return "action_find_by_location_and_cuisine"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
cuisine = tracker.get_slot("cuisine")
location = tracker.get_slot("location")
print(cuisine)
print(location)
print("flag value in Cuisine and Location")
print(flag)
# write the sql query here.
if flag==0:
query = "Select Name, Rating From Restaurant Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
query2 = "Select COUNT(Name), Rating From Restaurant Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
else:
query = "Select Name, Rating From LocationView Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
query2 = "Select COUNT(Name), Rating From LocationView Where Location = '%s' AND RestaurantID IN (SELECT RestaurantID FROM Cuisine WHERE Name = '%s') LIMIT 5" % (location,cuisine)
#pass the sql query to the getData method and store the results in `data` variable.
location_cuisine = getData(query)
location_cuisine_count= getData(query2)
print("data: ",location_cuisine)
dispatcher.utter_message(text="Find By Cuisine And Location ",json_message=location_cuisine)
dispatcher.utter_message(text="Number of places ",json_message=location_cuisine_count)
dispatcher.utter_message(text="آپ کس پرائس میں کھانا پسند کریں گے")
return []
By the time my flag which should be changed to 1 after being executed in Sublocation (which it does according to the terminal) it is changed to 0 when used again in any other function especially find_by_location_and_cuisine
Thank you for your help!

If you want to use the global flag, use
global flag
in the function you want to use it.
If you don’t mention this statement, the flag variable is considered as a local variable, i.e., a new local variable is created.

Related

how to work with foreign key field in django

Hi Everyone i am working work django framework, where i used to upload excel file in Dailytrip table, current i get car_mumber from car table, but now i need to store car_number from Car_team table also team_id, i am storing car_id and team_id in car_team table also i need to store team_id in dailytrip table automaticlly based on car_id(car_number) i am to much confuse how to i work that, pls help me out
models.py
class Car_team(BaseModel):
team = models.ForeignKey(
Team,
models.CASCADE,
verbose_name='Team',
null=True,
)
car=models.ForeignKey(
Car,
models.CASCADE,
verbose_name='Car',
null=True)
city =models.ForeignKey(
City,
models.CASCADE,
verbose_name='City',
)
start_date=models.DateField(null=True, blank=True)
end_date=models.DateField(null=True, blank=True)
views.py
def add_payout_uber_daily_data(request):
if request.method == 'POST':
form = UberPerformanceDataForm(request.POST, request.FILES, request=request)
if form.is_valid():
date = form.cleaned_data['date']
excel_file = request.FILES['file']
df = pd.read_excel(excel_file)
is_na = pd.isna(df['Date']).sum().sum() + pd.isna(df['Name']).sum().sum() + pd.isna(df['UUID']).sum().sum() + pd.isna(df['Net Fare With Toll']).sum().sum() + pd.isna(df['Trips']).sum().sum() + pd.isna(df['Uber KMs']).sum().sum() + pd.isna(df['CashCollected']).sum().sum() + pd.isna(df['UberToll']).sum().sum() + pd.isna(df['Tips']).sum().sum() + pd.isna(df['Hours Online']).sum().sum() + pd.isna(df['Ratings']).sum().sum() + pd.isna(df['Acceptance Rate']).sum().sum() + pd.isna(df['Cancellation Rate']).sum().sum()
error_list = []
if is_na > 0:
error_list.append('Found #N/A or blank values in the sheet. Please correct and re-upload')
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
date_match = True
for d in df['Date']:
if str(d.strftime("%Y-%m-%d")) != str(date):
date_match = False
break
if not date_match:
error_list.append('Some dates are not matching in excel')
if len(error_list) > 0:
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
DailyTrip.objects.filter(date=date).update(is_active=0)
for i in df.index:
uuid = df['UUID'][i]
driver_id = None
car_id = None
fleet_id = None
manager_id = None
try:
driver = Driver.objects.get(uber_uuid=uuid)
driver_id = driver.id
except Driver.DoesNotExist:
driver_id = None
#replce car code and store car_number,car_id,team_id via car_team only this logic need to change current get car_number direct car table but we need car_number vai foriegn key
try:
car = Car.objects.get(car_number=df["Car Number"][i])
car_id = car.id
manager_id = car.manager_id
except Car.DoesNotExist:
car_id = None
try:
fleet = Fleet.objects.get(name=df["Fleet Name"][i])
fleet_id = fleet.id
except Fleet.DoesNotExist:
fleet_id = None
name = df['Name'][i]
car_number = df['Car Number'][i]
fare_total = df['Net Fare With Toll'][i]
trips = df['Trips'][i]
pool_trips = 0
hours_online = df['Hours Online'][i]
total_km = df['Uber KMs'][i]
cash_collected = abs(df['CashCollected'][i])
toll = df['UberToll'][i]
tip_amount = df['Tips'][i]
fare_avg = float(fare_total)/int(trips)
fare_per_hour_online = float(fare_total)/float(hours_online)
fare_per_km = fare_total/total_km
trips_per_hour = trips/hours_online
km_per_trip = total_km/trips
rating = df['Ratings'][i]
acceptance_rate_perc = float(df['Acceptance Rate'][i])/100
driver_cancellation_rate = float(df['Cancellation Rate'][i])/100
obj, created = DailyTrip.all_objects.update_or_create(
date=date, uuid=uuid,
defaults={
'car_id': car_id,
'manager_id': manager_id,
'car_number': car_number,
'driver_id': driver_id,
'car_id': car_id,
'fleet_id': fleet_id,
'driver_name': name,
'fare_total': fare_total,
'trips': trips,
'pool_trips': pool_trips,
'hours_online': hours_online,
'total_km': total_km,
'cash_collected': cash_collected,
'toll': toll,
'tip_amount': tip_amount,
'fare_avg': fare_avg,
'fare_per_hour_online':fare_per_hour_online,
'fare_per_km':fare_per_km,
'trips_per_hour': trips_per_hour,
'km_per_trip': km_per_trip,
'rating': rating,
'acceptance_rate_perc': acceptance_rate_perc,
'driver_cancellation_rate': driver_cancellation_rate,
'is_active': 1,
'comments': None}
)
if len(error_list) > 0:
DailyTrip.objects.filter(date=date).update(is_active=0)
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
else:
messages.success(request, 'Daily Trips added Successfully...')
return redirect('/fleet/payout/daily_data/add/uber')
else:
form = UberPerformanceDataForm(initial={})
context = {
'menu_payout': 'active',
'submenu_daily_data': 'active',
'form': form,
}
return render(request, 'add_payout_uber_daily_data.html', context=context)
You can try that :
to get car_number from car_team -->
car_team = car_team.objects.objects.all().last() # to get the last car_team for example
car_number = car_team.car.car_number # to get the car number from the car_team
try:
car = Car.objects.get(car_number=df["Car Number"][i])
car_id = car.id
car1=Car_team.objects.filter(car_id=car_id)
if car1:
team_id=car1[0].team_id
else:
team_id=None
except Car.DoesNotExist:
car_id = None
team_id= None

How to bulk create or update in Django

I have to process an item report CSV file every 1 hour. The CSV contains 150k+ records for 1 account and there are multiple accounts in my system. I was working previously on rails and there was active record gem to handle this use case very efficiently. I am looking for an alternate to this gem in Django or any built in method that will be helpful to import such large data in bulk.
So far I have tried this code.
class ItemReportService:
def call(self, file_url):
with open(file_url, 'r') as file:
reader = csv.DictReader(file)
products = []
for row in reader:
product = self.process_product(row)
products.append(product)
self.update_products(products)
def process_product(self, row):
print(f'Processing sku: {row["SKU"]}')
product = Product.objects.filter(
sku=row['SKU']).first() or Product(sku=row['SKU'])
product.listing_title = row['Product Name']
product.listed_price = row['Price']
product.buy_box_price = row['Buy Box Item Price'] + \
row['Buy Box Shipping Price']
product.status = row['Lifecycle Status']
return product
def update_products(self, products):
Product.objects.bulk_update(
products,
[
'listing_title',
'listed_price',
'buy_box_price',
'Lifecycle Status'
]
)
It is raising this exception because when there is a new product it doesn't have primary key assigned to it
ValueError: All bulk_update() objects must have a primary key set.
Django 4.1 has new parameters for bulk_create(update_conflicts=bool and update_fields=[])
If your model has a field UNIQUE usually Django would ignore it when creating new data. But if you set the update_conflicts parameter to True, the fields inside update_fields will be updated.
You are not saving the product in the database before applying bulk_update.
I have checked your code for this purpose, you can use bulk_insert with an additional parameter
Model.objects.bulk_create(self.data, ignore_conflicts=True)
or
columns = ['column1', 'column2']
obj = Model.objects.filter(column1="sku").first()
if not obj:
obj = Model.objects.create(column1="sku")
obj.column1 = row["column1"] or obj.column1
obj.column2 = row["column2"] or obj.column2
items_to_be_inserted.append(obj)
In the end, you can do bulk update like
Model.objects.bulk_update(items_to_be_inserted, columns)
This will solve your problem.
I made this class function which can be used on any Django model in a project.
from django.db import models
class BaseModel(models.Model):
#classmethod
def bulk_create_or_update(
cls, uniques: list[str],
defaults: list[str],
data: list[dict]
):
# Get existing object list
data_dict, select = {}, None
for entry in data:
sub_entry, key = {}, ''
for uniq in uniques:
sub_entry[uniq] = entry[uniq]
key += str(entry[uniq])
data_dict[key] = entry
if not select:
select = models.Q(**sub_entry)
continue
select |= models.Q(**sub_entry)
records = cls.objects.filter(select).values('pk', *uniques)
existing = {}
for rec in records:
key = ''
for uniq in uniques:
key += str(rec[uniq])
existing[key] = rec
# Split new objects from existing ones
to_create, to_update = [], []
for key, entry in data_dict.items():
obj = cls(**entry)
if key not in existing:
to_create.append(obj)
continue
obj.pk = existing[key]['pk']
to_update.append(obj)
cls.objects.bulk_create(to_create, batch_size=1000)
cls.objects.bulk_update(to_create, defaults, batch_size=1000)
Let take an usage example
class Product(BaseModel)
price = models.IntegerField()
name = models.CharField(max_length=128, unique=True)
status = models.CharField(max_length=128)
if __name__ == '__main__':
data = [
{'price': 50, 'name': 'p1', 'status': 'New'},
{'price': 33, 'name': 'p2', 'status': 'Old'}
]
Product.bulk_create_or_update(uniques=['name'], defaults=['price', 'status'], data=data)
Any improvement suggestion of the code is welcome.

SQLAlchemy Order joined table by field in another joined table

My project requires that Orders are split into their individual lines which can be displayed in their own views I want these views to order the lines by eta which is a value in the Order table.
I have 3 tables with a 1>1 join on tables 1&2 and a many>many join on tables 2 and 3 defined by table 4 as follows:
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
eta = db.Column(db.DateTime())
order_lines = db.relationship('Line', backref='order', order_by=lambda: Line.id)
def __repr__(self):
return '<Order No. {}>'.format(self.increment_id)
class Line(db.Model):
id = db.Column(db.Integer, primary_key=True)
line_name = db.Column(db.String())
order_id = db.Column(db.Integer, db.ForeignKey('order.id'))
product_id = db.Column(db.String, db.ForeignKey('product.product_id'))
def __repr__(self):
return '<Line SKU: {}>'.format(self.line_sku)
class Line_view(db.Model):
id = db.Column(db.Integer, primary_key=True)
view_name = db.Column(db.String())
view_lines = relationship('Line',
secondary='line_view_join',
backref='views',
lazy='dynamic',
order_by= ***???*** ) #ordery by eta on Order table
def __repr__(self):
return '<View: {}>'.format(self.view_name)
class Line_view_join(db.Model):
__tablename__ = 'line_view_join'
id = db.Column(db.Integer(), primary_key=True)
line_id = db.Column(db.Integer(), db.ForeignKey('line.id', ondelete='CASCADE'))
view_id = db.Column(db.Integer(), db.ForeignKey('line_view.id', ondelete='CASCADE'))
I am trying to work out how to query table 3, Line_View and have the joined Lines ordered by the eta of Order table.
Such that when querying:
chosen_view = Line_view.query.filter_by(id = 1).one()
chosen_view.view_lines are ordered by Order.eta
I have Tried
class Line_view(db.Model):
id = db.Column(db.Integer, primary_key=True)
view_name = db.Column(db.String())
view_lines = relationship('Line',
secondary='line_view_join',
backref='views',
lazy='dynamic',
**order_by=lambda: asc(Line.order.eta))**
def __repr__(self):
return '<View: {}>'.format(self.view_name)
But this results in the error:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Line.order has an attribute 'eta'
Do you need to store the Line_views in the database? If not, you can query the Lines sorted by the eta attribute of the related order. Below, I create two orders with one line each, and then query the lines sorted by the eta attribute of their order:
eta = datetime(2019,10,10)
o = Order(eta = eta)
l = Line(order=o, line_name="sample")
db.session.add(o)
db.session.add(l)
eta = datetime(2019,11,11)
o1 = Order(eta = eta)
l1 = Line(order=o1, line_name="sample1")
db.session.add(o1)
db.session.add(l1)
db.session.commit()
lines = Line.query.join(Order).order_by(Order.eta)

Sqlite in Python

Hey guys I am trying to select my favorite person from the table by using their first name and then print out their first and middle name.I am also trying to make sure to parameterize the query. When I try to run the code it says KeyError: 'first_name' in my for loop of the assignmentRecords towards the bottom. Is even a step in the right direction or totally wrong?
# =============#
# imports #
# =============#
import sqlite3 #for working with sqlite version 3 databases
# ===============#
# constants #
# ===============#
SQL_FILE = "assignment_6.01-JonathanMaldonado.db"
SQL_CREATE_TABLE = """
CREATE TABLE person
(
person_id INTEGER PRIMARY KEY,
first_name TEXT,
middle_name TEXT,
age TEXT,
favorite_thing TEXT
)"""
SQL_DELETE_ASSIGNMENT = """
DELETE FROM person
WHERE person_id = ?
"""
SQL_INSERT_ASSIGNMENT = """
INSERT INTO person
(first_name,middle_name,age,favorite_thing)
VALUES
(?,?,?,?)
"""
SQL_SELECT_ASSIGNMENTS = """
SELECT
person_id,
first_name,
middle_name,
age,
favorite_thing
FROM person
"""
SQL_UPDATE_ASSIGNMENT = """
UPDATE person
SET age = ?
WHERE person_id = ?
"""
# ===============#
# functions #
# ===============#
def createPersonTable(dbConnection):
""" creates an assignment database table """
#fill in the function to create the table
#the SQL statement is provided as a constant
dbCursor = dbConnection.cursor()
dbCursor.execute(SQL_CREATE_TABLE)
dbCursor.close()
def deleteAssignmentByID(dbConnection,AGE):
""" deletes assignment records by their ID """
#fill in the function to delete a record from the assignment table
#the SQL statement is provided as a constant
#be sure to parameterize as needed and check that 1 record was deleted
dbCursor = dbConnection.cursor()
arguments = [
AGE,
]
dbCursor.execute(SQL_DELETE_ASSIGNMENT,arguments)
#make sure the record was deleted successfully
numberOfRecordsInserted = dbCursor.rowcount
if(numberOfRecordsInserted != 1):
errorMessage = "{} records were inserted when there should have been 1"
raise RuntimeError(errorMessage.format(numberOfRecordsInserted))
#close the cursor
dbCursor.close()
def insertAssignment(dbConnection,person):
""" inserts assignment records one at a time """
#fill in the function to insert a record
#the SQL statement is provided as a constant
#be sure to parameterize as needed and check that 1 record was inserted
dbCursor = dbConnection.cursor()
arguments = [
person["first_name"],
person["middle_name"],
person["age"],
person["favorite_thing"],
]
dbCursor.execute(SQL_INSERT_ASSIGNMENT,arguments)
#make sure the record was inserted successfully
numberOfRecordsInserted = dbCursor.rowcount
if(numberOfRecordsInserted != 1):
errorMessage = "{} records were inserted when there should have been 1"
raise RuntimeError(errorMessage.format(numberOfRecordsInserted))
#close the cursor
dbCursor.close()
def selectAllAssignments(dbConnection):
""" returns a list of all assignment records """
#fill in the function to return a list of assignment records
#the SQL statement is provided as a constant
dbCursor = dbConnection.cursor()
dbCursor.execute(SQL_SELECT_ASSIGNMENTS)
#build list of assignment records
persons = []
for record in dbCursor:
person = {
"person_id": record[0],
" first_name": record[1],
"middle_name": record[2],
"age": record[3],
"favorite_thing": record[4]
}
persons.append(person)
#close the cursor and return the list
dbCursor.close()
return persons
# ==========#
# main #
# ==========#
def main():
""" main method """
#connect to the database using the file name provided as a constant
dbConnection = sqlite3.connect(SQL_FILE)
#dropping table in case you need to re-run this multiple times
#no need to change this part
dbCursor = dbConnection.cursor()
try:
dbCursor.execute("DROP TABLE IF EXISTS person")
except Exception as e:
dbConnection.close()
raise #stop the rest of the script
#create the assignment table
#use the createAssignmentTable function and wrap in an appropriate try block
try:
createPersonTable(dbConnection)
except Exception as e:
#close the connection and stop
dbConnection.close()
raise #stop the rest of the script
#loop through the following assignment records and insert them
#use the insertAssignment function and wrap in an appropriate try block
persons = [
{
"first_name": "Demi",
"middle_name": "Rose",
"age": "22",
"favorite_thing": "Cute and funny",
},
{
"first_name": "Esmeralda",
"middle_name": "Arciga",
"age": "48",
"favorite_thing": "Lovly Mother",
},
{
"first_name": "Dead",
"middle_name": "Pool",
"age": "32",
"favorite_thing": "Superhero",
}
]
for person in persons:
try:
insertAssignment(dbConnection,person)
except Exception as e:
#roll back the transaction and stop
dbConnection.rollback()
dbConnection.close()
raise #stop the rest of the script
else:
#commit the transaction
dbConnection.commit()
#select all of the assignment records and store in a variable
#use the selectAllAssignments function and wrap in an appropriate try block
try:
assignmentRecords = selectAllAssignments(dbConnection)
except Exception as e:
#roll back the transaction and stop
dbConnection.rollback()
dbConnection.close()
raise #stop the rest of the script
else:
pass #no need to commit since it was just a select
#loop through the assignment records
#print the title and due date of each and then delete that record
#use the deleteAssignmentByID function and wrap in an appropriate try block
for person in assignmentRecords:
try:
print("{} {} is {} old and {}".format(person["first_name"],person["middle_name"],person["age"],person["favorite_thing"]))
deleteAssignmentByID(dbConnection,person["person_id"])
except Exception as e:
#roll back the transaction and stop
dbConnection.rollback()
dbConnection.close()
raise #stop the rest of the script
else:
#commit the transaction
dbConnection.commit()
#close the database connection
dbConnection.close()
# kick off main
if(__name__ == "__main__"):
main()

Dictionary with functions versus dictionary with class

I'm creating a game where i have the data imported from a database, but i have a little problem...
Currently i get a copy of the data as a dictionary, which i need to pass as argument to my GUI, however i also need to process some data, like in this example:
I get the data as a dict (I've created the UseDatabase context manager and is working):
def get_user(name: str, passwd: str):
user = {}
user['name'] = name
user['passwd'] = passwd
with UseDatabase() as cursor:
_SQL = "SELECT id, cash, ruby FROM user WHERE name='Admin' AND password='adminpass'"
cursor.execute(_SQL)
res = cursor.fetchall()
if res:
user['id'] = res[0][0]
user['cash'] = res[0][1]
user['ruby'] = res[0][2]
return user
return res
.
.
.
def get_activities():
with UseDatabase() as cursor:
_SQL = "SELECT * FROM activities WHERE user_id='2'"
cursor.execute(_SQL)
res = cursor.fetchall()
if res:
ids = [i[0] for i in res]
activities = {}
for i in res:
activities[i[0]] = {'title':i[1],'unlock':i[2],'usr_progress':i[3]}
return (ids, activities)
return res
Need it as a dict in my GUI ("content" argument):
class SideBar:
def __init__(self, screen: 'pygame.display.set_mode()', box_width: int, box_height: int, content: dict, font: 'font = pygame.font.Font()'):
#content dict: {id: {'title':'','unlock':'','usr_progress':''},...}
self.box_width = box_width
self.box_height = box_height
self.box_per_screen = screen.get_height() // box_height
self.content = content
self.current_box = 1
self.screen = screen
self.font = font
self.generate_bar()
def generate_bar (self):
active = [i for i in self.content.keys() if i in range(self.current_box, self.current_box+self.box_per_screen)]
for i in range(self.box_per_screen):
gfxdraw.box(self.screen,pygame.Rect((0,i*self.box_height),(self.screen.get_width()/3,self.screen.get_height()/3)),(249,0,0,170))
self.screen.blit(self.font.render(str(active[i]) + ' - ' + self.content[active[i]]['title'], True, (255,255,255)),(10,i*self.box_height+4))
for i in range(self.box_per_screen):
pygame.draw.rect(self.screen,(50,0,0),pygame.Rect((0,i*self.box_height),(self.screen.get_width()/3,self.screen.get_height()/3)),2)
But still need to make some changes in the data:
def unlock_act(act_id):
if user['cash'] >= activities[act_id]['unlock'] and activities[act_id]['usr_progress'] == 0:
user['cash'] -= activities[act_id]['unlock']
activities[act_id]['usr_progress'] = 1
So the question is: in this situation should i keep a copy of the data as dict, and create a class with it plus the methods i need or use functions to edit the data inside the dict?

Resources