简体   繁体   中英

Python : unable to connect to localhost using flask app

I'm a beginner in Flask and we run a simple web app at univeristy where you connect to a localhost and you get a simple Hello World text. However when I try to run the app after the flask app loads with the code below:

* Serving Flask app "my_app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Then i press CTRL +C to quit and then I try to run my app to connect to the webpage using the command

curl localhost:5000/

and I get the error message:

curl : Prefix of  URI not recognised.
  At line:1 char:1
    + curl localhost:5000/
    + ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotImplemented: (:) [Invoke-WebRequest], NotSupportedException
    + FullyQualifiedErrorId : 
    WebCmdletIEDomNotSupportedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

I have tried changing the command to curl.exe localhost:500/ but the result is the same. I have my code below for the web app:

from flask import Flask
app = Flask(__name__)

 @app.route('/')
 def hello_world():
     return 'Hello World!'
 @app.route('/<name>')
 def hello_name(name):
     return f'Hello {name}!\n'

 if __name__ == '__main__':
       app.run(host='0.0.0.0')

I would appreciate your help with guiding me to run my app. Thank you in advance.

EDIT: the problem was simply that I would terminate my app without opening a shell to connect to the localhost. Thank you for your responses very much

If I'm understanding your issue correctly it's that you can't get back your website's response from the server.

This makes complete sense. You are running your app, then stopping it when you hit 'CTRL + C'.

Then you are trying to connect to the server, which you've already stopped. You need to leave the server running (don't hit 'CTRL + C') then use a web browser and type in http://0.0.0.0:5000/ and you should see your 'hello world' back.

Alternatively, you can open a separate tab in terminal/command prompt and use the curl command.

You said it yourself:

Then i press CTRL +C to quit

That is when you terminate the server, so it would just cease to exist, and obviously not accept any incoming connections.

You need to leave the process running until you want to terminate it. So, go to another terminal, without first terminating the server, and then you will see curl manages to retrieve the page.

You are terminate the app. Instead press CTRL + T to open a new tab.

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