【发布时间】:2017-09-23 21:59:34
【问题描述】:
我正在使用 peewee (ORM) 创建一个小型 Python-MySQL 应用程序。 我的代码在单个文件中完美运行,如下所示:
import os
from peewee import *
from playhouse.db_url import connect
# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')
db.connect()
class Users(Model):
users_id = PrimaryKeyField()
username = CharField()
password = CharField()
mobile_number = CharField()
created_at = DateTimeField()
updated_at = DateTimeField()
class Meta:
database = db
class User_profiles(Model):
users_id = IntegerField()
user_profiles_id = PrimaryKeyField()
profile_name = CharField()
address = CharField()
created_at = DateTimeField()
updated_at = DateTimeField()
class Meta:
database = db
Users.create(username = "Adam", password = "Dummy1", mobile_number = "1234567891")
User_profiles.create(users_id=4,profile_name="shop", address="Delhi")
用户和用户配置文件是使用 peewee 定义的模型。我可以在单个文件中使用这些模型创建条目。
现在我尝试将其拆分为 3 个文件:main.py、users.py、userprofiles.py main.py - 应该调用 users.py 和 userprofiles.py 的主文件
我的main.py
import os
from peewee import *
from playhouse.db_url import connect
# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')
db.connect()
Users.create(username = 'testname', password = '@88@@', mobile_number='1234567811'):
我的users.py:
import os
from peewee import *
from playhouse.db_url import connect
# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
# db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')
db.connect()
class Users(Model):
users_id = PrimaryKeyField()
username = CharField()
password = CharField()
mobile_number = CharField()
created_at = DateTimeField()
updated_at = DateTimeField()
class Meta:
database = db
我的userprofiles.py:
import os
from peewee import *
from playhouse.db_url import connect
# Connect to the database URL defined in the environment, falling
# back to a local MySql database if no database URL is specified.
# db = connect(os.environ.get('DATABASE') or 'mysql://testdb:testdb@127.0.0.1:3306/db')
# db.connect()
class User_profiles(Model):
users_id = IntegerField()
user_profiles_id = PrimaryKeyField()
profile_name = CharField()
address = CharField()
created_at = DateTimeField()
updated_at = DateTimeField()
class Meta:
database = db
如何在 main.py 中导入 users.py 和 userprofiles.py 以使用 peewee 在 main.py 中执行操作?
我正在尝试导入上述 py 文件并通过链接两个模型来执行 db 操作。 我是编码新手。 Python 入门
【问题讨论】:
-
users.py 和 userprofiles.py 的内容相同。我相信这是复制/粘贴错误?另外,到目前为止,您在 main.py 中尝试过什么?
-
@zmo 这是一个错误。我将重新编辑我的问题。
标签: python python-2.7 class python-module peewee