I'm creating an API with flask_restful, and I want to search for example with two parameters that will be passed by GET, tag and author.
with the code below I can do this. However, it's necessary that I should pass the two parameters. I want whatever the parameter the user passed still search for it,
Exempli gratia: if I passed tag=tech the response should have all the news with tag tech and with all authors if also I passed the author it should consider tag as all -i think u got it-
class ArticleAPI(Resource):
def get(self):
tag=request.args.get('tag','')
auth=request.args.get('author','')
news = News.objects.filter(topic=tag,author=auth).to_json()
return Response(news, mimetype="application/json", status=200)
i know i can do it long just like this, but it looks ugly :`(
if tag is not None and auth is not None :
news = News.objects.filter(topic=tag,author=auth).to_json()
elif tag is not None :
news = News.objects.filter(topic=tag).to_json()
elif auth is not None:
news = News.objects.filter(author=auth).to_json()
I'm using Flask_mongoengine
from flask_mongoengine import MongoEngine
db = MongoEngine()
def initialize_db(app):
db.init_app(app)