简体   繁体   中英

How Do I Pass A Parameter into A Get Request to A Flask Blueprint Python App?

I have a flask/blueprint app that works with hard-coded or all() GET requests. This is the code in api.py :

from flask import Blueprint

from ..extensions import db
from ..models.users import Users

api = Blueprint('api', __name__)

@api.route('/user/<name>')
def get_user(email):
    users = Users.query.first()

    return {'users': users.email}

The above code works and doing GET http://127.0.0.1:5000/user/anythingHere in Postman returns:

{
    "users": "test@example.com"
}

Which is correct and corresponds with my database. But when I modify the code in api.py to look like this:

from flask import Blueprint

from ..extensions import db
from ..models.users import Users

api = Blueprint('api', __name__)

@api.route('/user/<name>')
def get_user(email):
    users = Users.query.filter_by(email='<name>').first()

    return {'users': users.email}

And in Postman run http://127.0.0.1:5000/user/test@example.com hoping that test@example.com will populate <name> in filter_by(email='<name>') , but obviously this doesn't work as indicated by the fact that I get TypeError: get_user() got an unexpected keyword argument 'name' in my terminal and this in Postman:

<!doctype html>
<html lang=en>
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or
    there is an error in the application.</p>

So how do I pass the email parameter from the GET request to the get_user function?

You need to pass email into the function as email not <email> like this:

from flask import Blueprint

from ..extensions import db
from ..models.users import Users

api = Blueprint('api', __name__)

@api.route('/user/<email>')
def get_user(email):
    users = Users.query.filter_by(email=email).first()

    return {'users': users.email}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM