我是python环境的新手,所以我创建了一个示例小项目来试试这个:
- 创建手机品牌并保存到brands.pkl文本字段:“品牌名称”
- 通过下拉列表从先前创建的品牌中选择品牌并保存到 models.pkl 文本字段中创建手机模型:手机名称下拉列表:已创建品牌。
但我还没有找到解决它的方法(在 sql 中我可以通过 id 使用外键)。
谢谢你。
这是我的示例代码:
def phones(self):
saved_phones= util.load_phones()
return json.dumps(saved_phones)
@cherrypy.expose
def new_brands(self, *args, **kwargs):
try:
saved_brands = util.load_brands()
brand = {'name': kwargs['brand_name']}
try:
brand['id'] = saved_brands[-1]['id'] + 1
except IndexError:
brand['id'] = 1
saved_brands.append(brand)
util.save_brands(saved_brands)
return json.dumps(brand)
except Exception as e:
return json.dumps({'error': str(e)})
@cherrypy.expose
def new_phones(self, *args, **kwargs):
try:
saved_phones = util.load_phones()
phone = {'model': kwargs['phone_model']}
try:
phone['id'] = saved_module[-1]['id'] + 1
except IndexError:
phone['id'] = 1
saved_phones.append(phone)
util.save_phones(saved_phones)
return json.dumps(phone)
except Exception as e:
return json.dumps({'error': str(e)})
def save_phones(phones):
pickle.dump(phones, open('phones.pkl', 'wb'))
def load_phones():
try:
saved_phones = pickle.load(open('phones.pkl', 'rb'))
except IOError:
saved_phones = []
return saved_phones
def get_modul(phones, phone_id):
for phone in phones:
if phone['id'] == phone_id:
return phone
# if
# for
return None
def save_brands(brands):
pickle.dump(brands, open('brands.pkl', 'wb'))
def load_brands():
try:
saved_brands = pickle.load(open('brands.pkl', 'rb'))
except IOError:
saved_brands = []
return saved_brands
def get_modul(brands, brand_id):
for brand in brands:
if brand['id'] == brand_id:
return brand
# if
# for
return None