我的脚本download.py
包含:
import argparse
import models
parser = argparse.ArgumentParser()
parser.add_argument("--db_path", required=True)
args = parser.parse_args()
models.py
:
import peewee
database = peewee.SqliteDatabase("wee.db")
class Artist(peewee.Model):
name = peewee.CharField()
class Meta:
database = database
class Album(peewee.Model):
artist = peewee.ForeignKeyField(Artist)
title = peewee.CharField()
release_date = peewee.DateTimeField()
publisher = peewee.CharField()
media_type = peewee.CharField()
class Meta:
database = database
而不是wee.db
我想在args.db_path
文件中使用download.py
的数据库路径。我怎么能这样做?
答案 0 :(得分:0)
您所要做的就是将您的arg传递给SqliteDatabase
构造函数。
好像你正在使用Django。如果是这种情况,您可以(并且应该)在settings.py
,as indicated on the docs.
修改
这是一个代码示例,说明如何使用您建议的方式对现有代码执行此操作(我仍然认为有更好的方法):
models.py
:
database_name = "wee_db"
def set_database_name(name):
database_name = name
database = peewee.SqliteDatabase(database_name)
download.py
:
models.set_database_name(args.db_path)
答案 1 :(得分:0)
这是一个可能的解决方案:
# download.py
import argparse
from models import DBManager
parser = argparse.ArgumentParser()
parser.add_argument("--db_path", required=True)
args = parser.parse_args()
DBManager(args.db_path)
# models.py
import peewee
class Artist(peewee.Model):
name = peewee.CharField()
class Album(peewee.Model):
artist = peewee.ForeignKeyField(Artist)
title = peewee.CharField()
release_date = peewee.DateTimeField()
publisher = peewee.CharField()
media_type = peewee.CharField()
class DBManager(object):
def __init__(self, db_path):
self.database = peewee.SqliteDatabase(db_path)
Artist._meta.database = self.database
Album._meta.database = self.database
self.database.connect()
self.database.create_tables([Artist, Album])