0

hello am trying to create flask api where user input the vaue and I will use that value to process my python code here is the code

`

app = Flask(__name__)
api = Api(app)

class Users(Resource):
    @app.route('/users/<string:name>/')
    def hello(name):
        namesource = request.args.get('name')
        return "Hello {}!".format(name)

print(namesource)  # here am trying to get the sitring/value in name source but i can't because it no       variable defines

api.add_resource(Users, name='users')
# For Running our Api on Localhost
if __name__ == '__main__':
    app.run(debug=True)

`

am trying to expect that i get that value/String outside of the function of api flask

1
  • 1
    You have this a little backwards. In your example, you cannot access namesource outside of the scope of the hello function. The solution here is to access the rest of the code you wish to run from within the scope of the hello function. So bundle the rest of the code you wish to run in a function, and call that function from within hello, passing in the variable namesource as an argument. Commented Dec 1, 2022 at 16:33

1 Answer 1

1

You are trying to access the variable namesource outside of the function hello. You can't do that. You can access the variable name outside of the function hello because it is a parameter of the function. You can fix it by making a global variable.

app = Flask(__name__)
api = Api(app)

namesource = None

class Users(Resource):
    @app.route('/users/&lt;string:name&gt;/')
    def hello(name):
        global namesource
        namesource = request.args.get('name')
        return "Hello {}!".format(name)

print(namesource)

api.add_resource(Users, name='users')
# For Running our Api on Localhost
if __name__ == '__main__':
    app.run(debug=True)
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried that but i get the none value
That is because you are printing namesource before assigning it. You can give it a default starting value, or print it inside your hello function (recommended).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.