简体   繁体   English

如何路由我的 api 呼叫,我通过用户在 Flask SQLAlchemy 中的用户名获取用户的位置

[英]How do I route my api call where I get the location of a user by their username in Flask SQLAlchemy

I'm trying to make a route where I get the location (which they enter when they sign up) of the user by their username.我正在尝试通过用户名获取用户位置(他们在注册时输入)的路线。 I'm not sure how to do it.我不知道该怎么做。

here is my table这是我的桌子

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), nullable=False, unique=True)
    password = db.Column(db.String(), nullable=False)
    location = db.Column(db.String(), nullable=True)

    def __init__(self, username, password, location):
        self.username = username
        self.password = password
        self.location = location

class UserSchema(ma.Schema):
    class Meta:
        fields = ("id", "username", "password", "location")

user_schema = UserSchema()
many_users_schema = UserSchema(many=True)

here is my route这是我的路线

@app.route("/location/get/data/<username>", methods=["GET"])
def get_location_by_username(username):
    user_id = db.session.query(User.id).filter(User.username == username).first()[0]
    user_location = db.session.query(User).filter(User.user_id == username).first()[0]
    return jsonify(user_schema.dump(user_location))

Here is the simple method of getting location from the front-end when user enters it HTML Part:这是用户输入时从前端获取位置的简单方法 HTML 部分:

<html>
    <head>
       <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    </head>
    <script>
        function submit(){
            var location = document.getElementById('location').value;
            $.get('/location',{location : location});
        }
    </script>
    <body>
        <input type = 'text' id = 'location' placeholder = 'location'>
        <button onclick = 'submit()'>Submit</button>
    </body>
</html>

Flask API Part: Flask API 零件:

@app.route('/location', methods = ['GET','POST'])
def location():
    user_loc = request.args.get('location');
    print(user_loc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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