2017-03-07 3 views
0

私のサーバーは、クライアントからのヘッダーにAPIキーを使用して要求を受け取ることで接続を確実にする必要があります。私はFlaskデコレータを使用してこれを組み込むのが難しいと思っています。FlaskとPyMongoを使用したヘッダーでのAPIキーを使用した接続のテスト

  1. 私たちはクライアントに要求を受け取るために使用されるAPIキーを提供しました。

  2. すべてのリクエストが行われるたびに、私たちはクライアントに照会し、データベースに更新を掲載するためにクライアントを認証します。

  3. Swagger API定義には、Flask Decoratorと対応する機能を使用して実装する必要があるHeaderにあるAPIキーのパラメータがあります。

私は以下のFlaskアプリケーションコードを書いています。ヘッダーでAPIを受け取ると、このサーバーエラーを修正できません。

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:[email protected]: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の定義は以下の通りです:

"parameters": [ 
        { 
         "name": "X-API-Key", 
         "in": "header", 
         "required": true, 
         "type": "string" 
        }, 

あなたは親切にどのように私は、クライアントが入力した私に基づいてAPIキーを持っています。このAPIキー認証を組み込むことができます助言することができサーバーは確認と認証が必要ですか?ありがとう。

答えて

1

着信要求データにアクセスするには、グローバル要求オブジェクトを使用できます。クライアントが必要なヘッダーで要求を送信するとき、あなたは着信要求ヘッダrequest.headersにアクセスすることができます

、ヘッダは、オブジェクトのような辞書です:

from flask import request 

@app.route('/api') 
def home(): 
    key = request.headers.get('API-Key') 
    print(key) 
    return 'Got %s key'%key 
カールをテストするには

またはhttpie

$ http get localhost:port/api API-Key:key-goes-here12458 
$ curl -H "API-Key:key-goes-here12458" localhost:port/api 
+0

おかげさまで、あなたの指針は私を助け、多くの労働時間を節約しました。 – Mari

関連する問題