我运行带有api函数的Web服务,该函数使用我创建的与pymongo进行MongoDB交互的方法。
post附带的json数据可能包含也可能不包含字段:firm
。我不想为不包含firm
字段的帖子创建新方法。
因此,我想使用firm
中的pymongo.find
(如果确实存在),或者如果不存在,我只想跳过它。 如何使用一种api函数和一种pymongo方法来做到这一点?
API函数:
@app.route(f'/{API_PREFIX}/wordcloud',methods=['POST'])
def generate_wc():
request_ = request.get_json()
firm = request_.get("firm").lower()
source = request_["source"]
since = datetime.strptime(request_["since"],"%Y-%m-%d")
until = datetime.strptime(request_["until"],"%Y-%m-%d")
items = mongo.get_tweets(firm,since,until)
...
pymongo方法:
def get_tweets(self,firm: str,since: datetime,until: datetime):
tweets = self.DB.tweets.find(
{
# use firm here if it exists (I mean not None),else just get items by date
'date': {'$gte': since,'$lte': until}
})
...
第二个代码在find
中的注释行中。
谢谢。