我正在使用peewee(ORM)創建一個小型Python-MySQL應用程序。 我的代碼完全在一個單一的文件,內容如下:如何在單獨的主python文件中鏈接多個python類?
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:[email protected]: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")
用戶&的UserProfiles如使用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:[email protected]:3306/db')
db.connect()
Users.create(username = 'testname', password = '@[email protected]@', 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:[email protected]: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:[email protected]: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
如何導入users.py和userprofiles.py在main.py執行使用peewee內main.py行動?
我想導入上面的py文件並通過鏈接兩個模型來執行數據庫操作。 我是一個編碼新手。開始使用Python的
users.py和userprofiles.py都具有相同的內容。我相信這是一個複製/粘貼錯誤?另外,你在main.py中嘗試過了些什麼? – zmo
@zmo這是一個錯誤。我會重新編輯我的問題。 – thepassionatecoder
請參閱如何創建[mcve] –