如何使用 python falcon rest api 为多个用户级别创建带有令牌的用户身份验证

How to create user authentication with tokens for multiple user levels with a python falcon rest api

我使用 python 猎鹰 api 创建了休息 api。它是访问特定银行 atm 的预测值并读取、更新、删除值。

import falcon
import MySQLdb
import json


import re
import mysql.connector
from mysql.connector import  Error

class TesResource:

def on_get(self, req, resp):

    try:
        atmid=req.get_param('atm_key_id')
        datestart=req.get_param('prediction_date_start')
        dateend=req.get_param('prediction_date_end')

        if atmid is None or atmid=="" or datestart is None or dateend is None:
            resp.body=json.dumps({'error': 'Parameter is invalid'})
            resp.status=falcon.HTTP_500
            return resp

        conn = mysql.connector.connect(host='localhost', database='bank', user='root', password='', autocommit=True)
        if conn.is_connected():
            print('connected')

        cursor=conn.cursor()

        #q="SELECT prediction_amount FROM prediction WHERE atm_key_id=5 AND (prediction_date BETWEEN '2017-10-01' AND '2017-10-1')"
        q="SELECT prediction_amount FROM prediction WHERE atm_key_id=%s AND (prediction_date BETWEEN %s AND %s)" 
        #q=("SELECT * FROM prediction")
        cursor.execute(q,(atmid, datestart, dateend,))
        rows=cursor.fetchall()

        output={'tes':[]}
        for row in rows:

            #data={"key":row[0], "amount":float(row[2])}
            data={"amount":float(row[0])}
            output['tes'].append(data)

        resp.status=falcon.HTTP_200
        resp.body=json.dumps(output, encoding='utf-8')
        cursor.close()
        conn.close()

    except Exception as e:
        resp.body=json.dumps({'error':str(e)})
        resp.status=falcon.HTTP_500
        return resp

def on_put(self, req, resp):

    try:


        atmid=req.get_param('atm_key_id')
        date=req.get_param('prediction_date')
        amount=req.get_param('prediction_amount')
        if atmid is None or atmid=="" or date is None or amount is None:
            resp.body=json.dumps({'error': 'Parameter is invalid'})
            resp.status=falcon.HTTP_500
            return resp

        conn = mysql.connector.connect(host='localhost', database='bank', user='root', password='', autocommit=True)
        if conn.is_connected():
            print('connected')

        cursor=conn.cursor()

        q="""UPDATE `prediction` SET `prediction_amount`=%s WHERE atm_key_id=%s AND prediction_date=%s """
        cursor.execute(q,(amount, atmid, date,))
        conn.commit()
        cursor.close()

        output={'status':"Data successfully updated"}

        resp.status=falcon.HTTP_200
        data_resp=json.dumps(output, encoding='utf-8')
        resp.body=data_resp


    except Exception as e:
        conn.rollback()
        resp.body=json.dumps({'error':str(e)})
        resp.status=falcon.HTTP_500
        return resp


def on_delete(self, req, resp):

    try:
        atmid=req.get_param('atm_key_id')
        date=req.get_param('prediction_date')
        if atmid is None or atmid=="" or date is None:
            resp.body=json.dumps({'error': 'Parameter is invalid'})
            resp.status=falcon.HTTP_500
            return resp

        conn = mysql.connector.connect(host='localhost', database='bank', user='root', password='', autocommit=True)
        if conn.is_connected():
            print('connected')

        cursor=conn.cursor()

        q="""DELETE FROM `prediction` WHERE atm_key_id=%s AND prediction_date=%s"""

        cursor.execute(q, (atmid, date,))
        conn.commit()
        cursor.close()

        output={'status':"Data successfully deleted"}

        resp.status=falcon.HTTP_200
        data_resp=json.dumps(output, encoding='utf-8')
        resp.body=data_resp

    except Exception as e:

        conn.rollback()
        resp.body=json.dumps({'error':str(e)})
        resp.status=falcon.HTTP_500
        return resp

有两个用户级别。每个人都可以获得特定日期或日期范围(访问级别 1)的预测值。但是只有经过授权的人才能更新或删除预测值(访问级别 2)。我有一个用户 mysql table。它以用户名、用户 ID 和 access_level(1 或 2)作为列。如何使用令牌创建用户身份验证?任何见解都会非常有帮助。

您可以创建一个身份验证装饰器,它将检查用户是否具有访问级别 2。在 on_updateon_delete.

上使用此装饰器

您可以使用 middleware,并在处理请求之前检查路径和令牌以及其他参数。这是最干净的方法,因为您可以为每个级别添加多个中间件,并让资源清理并与此特权级别逻辑分离。

查看 AuthMiddleware 示例,您可以分析请求并引发未经授权的异常 HTTP_401。与HTTP标准一致。

要添加多个中间件,您可以使用 falcon API 构造函数。

app = falcon.API(middleware=[
    AuthMiddleware(),
    UserPrivilegeMiddleware()
])