这里是烧瓶初学者
我有一个烧瓶应用程序,该应用程序将数据存储在数据库中。我正在尝试根据country_code
或price_type
等用户参数来过滤数据库。
现在,我在database.py
中具有多个过滤器功能,如下所示:
class DatabaseService:
@staticmethod
def read_list():
items = Price.query.all()
return {
"items": items
}
@staticmethod
def filter_prices_cc(country_code):
if country_code is not None:
items = Price.query.filter(country_code == country_code)
return {
"items": items
}
@staticmethod
def filter_prices_pt(price_type):
if price_type is not None:
items = Price.query.filter(price_type == price_type)
return {
"items": items
}
而且我在controller.py
中按如下方式调用这些方法:
@ns.route("/")
class Prices(Resource):
def get(self):
country = request.args.get('country_code')
price_type = request.args.get('price_type')
if country is not None:
return DatabaseService.filter_prices_cc(country)
if price_type is not None:
return DatabaseService.filter_prices_pt(price_type)
else:
return DatabaseService.read_list()
是否有更有效的方法来更改过滤器方法,以便根据request.args.get()
来过滤数据库?类似于:在database.py
中定义一种过滤方法,该方法将request.args.get()
中的值用作数据并过滤数据
我必须获得以下情况:
country_code
,则用它过滤数据库price_type
,则用它过滤数据库price_type
和country_code
,请按它们的组合过滤数据库样本数据:
{
"items": [
{
"id": 1,
"value": 21.4,
"start": "2020-05-12T00:00:00+02:00",
"end": "2020-05-12T01:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 2,
"value": 18.93,
"start": "2020-05-12T01:00:00+02:00",
"end": "2020-05-12T02:00:00+02:00",
"country_code": "DE",
"price_type": "DAY_AHEAD"
},
{
"id": 3,
"value": 18.06,
"start": "2020-05-12T02:00:00+02:00",
"end": "2020-05-12T03:00:00+02:00",
"country_code": "LU",
"price_type": "DAY_AHEAD"
},
{
"id": 4,
"value": 17.05,
"start": "2020-05-12T03:00:00+02:00",
"end": "2020-05-12T04:00:00+02:00",
"country_code": "DE",
"price_type": "TODAY"
}]}
我不确定这是否正确,但是您可以将request.args.get()
中的值传递为**kwargs
:
database.py
看起来像是:
class DatabaseService:
@staticmethod
def read_list(**filters):
items = Price.query.filter_by(**filters).all()
return {
"items": items
}
和controller.py
为:
@ns.route("/")
class Prices(Resource):
def get(self):
country = request.args.get('country_code')
price_type = request.args.get('price_type')
return DatabaseService.read_list(**request.args)
基于您是否具有country_code
或price_type
,过滤应该起作用
这可能对您很有趣: