Rest 使用Flask和PyMongo在标头中使用API键测试连接性
我的服务器必须通过从客户端接收头中带有API密钥的请求来确保连接。我发现使用烧瓶装饰器很难将其合并Rest 使用Flask和PyMongo在标头中使用API键测试连接性,rest,api,flask,pymongo,Rest,Api,Flask,Pymongo,我的服务器必须通过从客户端接收头中带有API密钥的请求来确保连接。我发现使用烧瓶装饰器很难将其合并 我们向客户提供了API密钥,用于接收请求 当发出每个请求时,我们都会检查并验证客户端是否将更新发布到我们的数据库中 Swagger API定义具有位于标头中的API键参数,该参数需要使用Flask Decorator和相应的函数实现 我已经编写了以下Flask应用程序代码。在接收报头中的API时,我无法纠正这个服务器错误 from flask import Flask, render_templa
from flask import Flask, render_template, url_for, request, session, redirect,jsonify
from flask_pymongo import PyMongo
import json
from bson.json_util import dumps
import bcrypt
import os
from binascii import hexlify
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'demo'
app.config['MONGO_URI'] = 'mongodb://xxxx:xxxx@xxxxxxx.mlab.com:57158/demo'
mongo = PyMongo(app)
@app.route('/addapi')
def addapi():
users = mongo.db.users
api_key=users.insert({"name":"apikey","X-API-Key":"69222c9b-7858-4eef-a218-039c8cd2bc6e"})
return 'API Key stored'
@app.route('/test/<string:apikey_given_by_user_in_the_header>',methods=['GET'])
"""I have a doubt in the above line that How Can I receive the API Key in the header and check if that is available in my database. This is for testing the connectivity using the Valid API Key."""
def test(apikey_given_by_user_in_the_header):
users=mongo.db.users
api_record=users.find_one({'name':"apikey"})
actual_API_key=api_record['X-API-Key']
if actual_API_key==apikey_given_by_user_in_the_header
return "API is available"
return "Invalid API Key"
如果客户端必须输入API密钥,我的服务器需要根据API密钥进行检查和验证,请告知我如何合并此API密钥验证?谢谢
要访问传入请求数据,可以使用全局请求对象
当客户端发送带有您需要的标题的请求时,您可以访问传入请求标题request.headers
,标题是类似字典的对象:
from flask import request
@app.route('/api')
def home():
key = request.headers.get('API-Key')
print(key)
return 'Got %s key'%key
使用curl或httpie进行测试
$ http get localhost:port/api API-Key:key-goes-here12458
$ curl -H "API-Key:key-goes-here12458" localhost:port/api
要访问传入请求数据,可以使用全局请求对象
当客户端发送带有您需要的标题的请求时,您可以访问传入请求标题request.headers
,标题是类似字典的对象:
from flask import request
@app.route('/api')
def home():
key = request.headers.get('API-Key')
print(key)
return 'Got %s key'%key
使用curl或httpie进行测试
$ http get localhost:port/api API-Key:key-goes-here12458
$ curl -H "API-Key:key-goes-here12458" localhost:port/api
非常感谢,你的指导帮了我很多,节省了很多工作时间。非常感谢,你的指导帮了我很多,节省了很多工作时间。