我是python环境中的新手, 所以我创建了一个示例小项目来试试这个:
但是我没有找到关系它的解决方案(在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
答案 0 :(得分:2)
也许你真的想要一个sql数据库? sqlite3
绑定与开箱即用的python一起提供,并且您可以在最短的时间内转换到更强大的数据库。