我上课了
class Foo():
def some_method():
pass
Run Code Online (Sandbox Code Playgroud)
和同一模块中的另一个类:
class Bar():
def some_other_method():
class_name = "Foo"
#can I access the class Foo above using the string "Foo"?
Run Code Online (Sandbox Code Playgroud)
我希望能够Foo
使用字符串"Foo" 访问该类.
如果我使用另一个模块,我可以这样做:
from project import foo_module
foo_class = getattr(foo_module, "Foo")
Run Code Online (Sandbox Code Playgroud)
我可以在同一个模块中做同样的事情吗?
IRC中的人建议我使用映射字典将字符串类名映射到类,但如果有更简单的方法,我不想这样做.
我有一个使用Flask-SQLAlchemy的Flask应用程序,我正在尝试将其配置为使用Flask-Restless软件包使用多个数据库.
根据文档(http://pythonhosted.org/Flask-SQLAlchemy/binds.html),配置模型以使用多个数据库__bind_key__
似乎非常简单.
但它似乎对我不起作用.
我创建我的应用程序并初始化我的数据库,如下所示:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
SQLALCHEMY_DATABASE_URI = 'postgres://db_user:db_pw@localhost:5432/db_name'
SQLALCHEMY_BINDS = {
'db1': SQLALCHEMY_DATABASE_URI,
'db2': 'mysql://db_user:db_pw@localhost:3306/db_name'
}
app = Flask(__name__)
db = SQLALchemy(app)
Run Code Online (Sandbox Code Playgroud)
然后定义我的模型,包括__bind_key__
,它应告诉SQLAlchemy它需要使用哪个DB:
class PostgresModel(db.Model):
__tablename__ = 'postgres_model_table'
__bind_key__ = 'db1'
id = db.Column(db.Integer, primary_key=True)
...
class MySQLModel(db.Model):
__tablename__ = 'mysql_model_table'
__bind_key__ = 'db2'
id = db.Column(db.Integer, primary_key=True)
...
Run Code Online (Sandbox Code Playgroud)
然后我像这样点燃Flask-Restless:
manager = restless.APIManager(app, flask_sqlalchemy_db=db)
manager.init_app(app, db)
auth_func = lambda: is_authenticated(app)
manager.create_api(PostgresModel,
methods=['GET'],
collection_name='postgres_model',
authentication_required_for=['GET'],
authentication_function=auth_func)
manager.create_api(MySQLModel,
methods=['GET'], …
Run Code Online (Sandbox Code Playgroud) 我可以使用MySQL GUI在所有表中搜索字符串吗?
或者是这样的:mySQL查询搜索数据库中的所有表格中的字符串?唯一的解决方案?
我对当前项目的要求之一是允许用户为其帐户选择时区,然后将此时区用于整个站点中的所有日期/时间相关功能.
我看到它的方式,我有两个选择:
date_default_timezone_set()
似乎使用date_default_timezone_set是要走的路,但我不确定我应该在哪里设置它.因为时区在用户之间会有所不同,而且整个站点都使用了DateTime,所以我需要将它设置在一个会影响所有页面的地方.
也许我可以写一个成功登录后设置它的事件监听器?如果我采用这种方法,它是否会在所有页面上保持设置,还是仅按页面设置?
我很想听听其他人如何接近这一点.
我有一个使用Flask-Restless来提供API的Flask应用程序.
我刚刚写了一些检查的身份验证
我希望能够为此编写一些单元测试,但我不确定如何因为我的函数使用请求对象.我应该嘲笑请求对象吗?
我会喜欢这方面的建议.
配置
API_CONSUMERS = [{'name': 'localhost',
'host': '12.0.0.1:5000',
'api_key': 'Ahth2ea5Ohngoop5'},
{'name': 'localhost2',
'host': '127.0.0.1:5001',
'api_key': 'Ahth2ea5Ohngoop6'}]
Run Code Online (Sandbox Code Playgroud)
验证方法
import hashlib
from flask import request
def is_authenticated(app):
"""
Checks that the consumers host is valid, the request has a hash and the
hash is the same when we excrypt the data with that hosts api key
Arguments:
app -- instance of the application
"""
consumers = app.config.get('API_CONSUMERS')
host = request.host
try:
api_key = next(d['api_key'] for d …
Run Code Online (Sandbox Code Playgroud) 我有一个Flask应用程序,为Django消费者提供API.我在我的消费者中使用请求库来访问API.
我的问题是这样的:当我测试我的API时,我得到POST数据request.form
,当我从我的消费者(使用请求库)点击它时,我得到了POST数据request.data
.
例如,
Flask app中的API端点:
@mod.route('/customers/', methods=['POST'])
def create_prospect():
customer = Customer()
prospect = customer.create_prospect(request.form)
return jsonify(prospect.serialize()), 201
Run Code Online (Sandbox Code Playgroud)
在Flask app中测试API端点:
def test_creating_prospect(self):
with self.app.app_context():
data = {'name': 'Test company and co'}
response = self.client.post(self.url, data=data)
...
Run Code Online (Sandbox Code Playgroud)
这填充request.form
在我的端点,工作正常.
从我的Django应用程序使用API,使用请求:
...
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data = {'name': 'Test company and co'}
response = requests.post(url, data=data, headers=headers)
Run Code Online (Sandbox Code Playgroud)
这填充request.data
在我的端点中,因为我正在检查request.form
信息而失败.
在写这个问题时我有一个想法; 也许json标题正在request.data
填充而不是request.form
?
任何输入赞赏.
编辑 - 我尝试将标题添加到我的测试中,工作正常: …
我有3个型号:
class Customer(Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
statemented_branch_id = Column(Integer, ForeignKey('branch'))
...
class Branch(Model):
__tablename__ = 'branch'
id = Column(Integer, primary_key=True)
...
class SalesManager(Model):
__tablename__ = 'sales_manager'
id = Column(Integer, primary_key=True)
branches = relationship('Branch', secondary=sales_manager_branches)
Run Code Online (Sandbox Code Playgroud)
和一个表构造:
sales_manager_branches = db.Table(
'sales_manager_branches',
Column('branch_id', Integer, ForeignKey('branch.id')),
Column('sales_manager_id', Integer, ForeignKey('sales_manager.id'))
)
Run Code Online (Sandbox Code Playgroud)
我希望能够得到所有Customers
的SalesManager
,这意味着所有有客户statemented_branch_id
在任何的Branch
ES的SalesManager.branches
关系.
我的查询看起来有点像这样:
branch_alias = aliased(Branch)
custs = Customer.query.join(branch_alias, SalesManager.branches).\
filter(Customer.statemented_branch_id == branch_alias.id)
Run Code Online (Sandbox Code Playgroud)
这显然是不对的.
我怎么能得到Customers
一个SalesManager
?
更新
当我尝试: …
我写了一个装饰器,试图检查我们是否有Flask POST路线的发布数据:
这是我的装饰者:
def require_post_data(required_fields=None):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
for required_field in required_fields:
if not request.form.get(required_field, None):
return jsonify({"error": "Missing %s from post data." %
required_field}), 400
else:
if not request.form:
return jsonify({"error": "No post data, aborting."}), 400
return f(*args, **kwargs)
return decorated_function
return decorator
Run Code Online (Sandbox Code Playgroud)
我有两条路线,一个是URL参数,另一条没有:
from flask import Blueprint, jsonify, request
mod = Blueprint('contacts', __name__, url_prefix='/contacts')
@mod.route('/', methods=['POST'])
@require_post_data(['customer_id', 'some_other_required_field'])
def create_contact():
# Do some business
@mod.route('/<int:contact_id>', methods=['POST'])
@require_post_data
def update_contact(contact_id):
# Do some business
Run Code Online (Sandbox Code Playgroud)
当我运行一个命中的测试时update_contact …
我有一个使用Flask-SQLAlchemy的Flask应用程序.在我的单元测试中,我初始化应用程序和数据库,然后调用db.create_all()
,由于某种原因它看起来它没有拿起我的任何模型,所以不创建任何表.
我正在使用这两个__tablename__
和__bind_key__
我的模型,因为我有两个数据库.
我的配置:
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_BINDS = {
'db1': SQLALCHEMY_DATABASE_URI,
'db2': SQLALCHEMY_DATABASE_URI
}
Run Code Online (Sandbox Code Playgroud)
setUp()
在我的单元测试中减少我的方法版本:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
class APITestCase(unittest.TestCase):
app = Flask(__name__)
db = SQLAlchemy(app)
db.create_all()
Run Code Online (Sandbox Code Playgroud)
这是我的两个模型的示例,每个模型来自一个绑定类型:
class Contact(db.Model):
__tablename__ = 'contact'
__bind_key__ = 'db1'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
...
def __init__(first_name, last_name):
self.first_name = first_name
self.last_name = last_name
...
class BaseUser(db.Model):
__tablename__ = 'User__GeneralUser'
__bind_key__ = 'db2'
id = db.Column(db.Integer, …
Run Code Online (Sandbox Code Playgroud) python ×7
flask ×6
mysql ×1
php ×1
sqlalchemy ×1
symfony ×1
timezone ×1
unit-testing ×1
werkzeug ×1