Как изменить порт flask

I want to change the host and port that my app runs on. I set host and port in app.run, but the flask run command still runs on the default 127.0.0.1:8000. How can I change the host and port that the

I want to change the host and port that my app runs on. I set host and port in app.run, but the flask run command still runs on the default 127.0.0.1:8000. How can I change the host and port that the flask command uses?

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)
set FLASK_APP=onlinegame
set FLASK_DEBUG=true
python -m flask run

Gino Mempin's user avatar

Gino Mempin

23.1k27 gold badges91 silver badges120 bronze badges

asked Jan 30, 2017 at 16:20

Marco Cutecchia's user avatar

Marco CutecchiaMarco Cutecchia

1,1552 gold badges9 silver badges14 bronze badges

0

The flask command is separate from the flask.run method. It doesn’t see the app or its configuration. To change the host and port, pass them as options to the command.

flask run -h localhost -p 3000

Pass --help for the full list of options.

Setting the SERVER_NAME config will not affect the command either, as the command can’t see the app’s config.


Never expose the dev server to the outside (such as binding to 0.0.0.0). Use a production WSGI server such as uWSGI or Gunicorn.

gunicorn -w 2 -b 0.0.0.0:3000 myapp:app

answered Jan 30, 2017 at 16:28

davidism's user avatar

0

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host="localhost", port=8000, debug=True)

Configure host and port like this in the script and run it with

python app.py

answered Mar 19, 2019 at 11:54

Gokhan Gerdan's user avatar

0

You can also use the environment variable FLASK_RUN_PORT, for instance:

export FLASK_RUN_PORT=8000
flask run
 * Running on http://127.0.0.1:8000/

Source: The Flask docs.

answered Mar 19, 2019 at 11:14

Akronix's user avatar

AkronixAkronix

1,7282 gold badges18 silver badges32 bronze badges

2

When you run the application server using the flask run command, the __name__ of the module is not "__main__". So the if block in your code is not executed — hence the server is not getting bound to 0.0.0.0, as you expect.

For using this command, you can bind a custom host using the --host flag.

flask run --host=0.0.0.0

Source

answered Jan 30, 2017 at 16:38

TeknasVaruas's user avatar

TeknasVaruasTeknasVaruas

1,4803 gold badges15 silver badges28 bronze badges

0

You can use this 2 environmental variables:

set FLASK_RUN_HOST=0.0.0.0
set FLASK_RUN_PORT=3000

answered Apr 30, 2021 at 14:56

Knemay's user avatar

KnemayKnemay

3021 gold badge6 silver badges12 bronze badges

2

You also can use it:

if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5002)

and then in the terminal run this

set FLASK_ENV=development
python app.py

answered Mar 27, 2020 at 17:03

StasNemy's user avatar

StasNemyStasNemy

1201 silver badge4 bronze badges

Change Port in Flask

We are about to learn how to change the port when we run our flask app through the command line interface and how to run the flask app on different ports at the same time and in different operating systems.

Change the Default Port in Flask

Mostly the beginners in Flask would use the following code to define a port where they want to run their flask app.

if __name__=='__main__':
    app.run(port=1000)

But instead of doing that, you can also do it on the command-line interface, which is the recommended way of doing it so that we will open a terminal in the directory where the flask app is located and then run the following command if you are working on Windows.

If you are working on a UNIX-based operating system, you must use the following command.

Technically we do not need to pass a file name like app.py because it automatically looks for app.py when we do not specify it, but to make it explicit, we added it there.

We will use the below command to run the flask app.

When we run it, the default configuration runs on port 5000, and we can go to the browser and check the port and what port is running.

Output:

Run Flask default configuration

Suppose we want to change the port for whatever reason. For example, we have a couple of flask apps, and in that case, we are creating different APIs and testing several APIs simultaneously, but they can not be on the same port, so we would have to change the port for at least one of them.

Let’s stop our server, and there are a couple of ways you can do this configuration variable. We look at the first method to define the port, and we can use the following command in the UNIX-based operating system.

export FLASK_RUN_PORT=8000

One way of doing it is on the Windows operating system.

When we run this command, we see in the output below that it runs on port 80. If we change this and it is working, we try to return to port 5000, but it no longer works.

Change port in Flask

You can also use the traditional way to define a specific port, as described in the beginning.

Full Source Code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def PORT_FUNC():
    return '<h2>Hi there, this is port testing<h2/>'

# set FLASK_APP=app.py
# unix command
# export FLASK_APP=app.py

# set FLASK_RUN_PORT=8000

# windows command
# flask run --port=80

# if __name__=='__main__':
#     app.run(port=1000)

Вопрос:

У меня есть сервер Flask, работающий через порт 5000, и это нормально. Я могу получить к нему доступ на http://example.com:5000

Но возможно ли просто получить к нему доступ по адресу http://example.com? Я предполагаю, что это означает, что я должен изменить порт с 5000 на 80. Но когда я пытаюсь сделать это на Flask, я получаю это сообщение об ошибке при запуске.

Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

Запуск lsof -i :80 возвратов

COMMAND   PID     USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
apache2   467     root    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2  4413 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14346 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14570 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14571 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14573 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)

Нужно ли мне сначала убить эти процессы? Это безопасно? Или есть другой способ сохранить работу Flask на порту 5000, но как-то перенаправить основной домен сайта?

Лучший ответ:

Таким образом, это вызывает это сообщение об ошибке, поскольку на порту 80 выполняется apache2.

Если это для разработки, я просто оставил бы его, как на порту 5000.

Если он для производства либо:

Не рекомендуется

  • Сначала остановите apache2;

Не рекомендуется указывать в документации:

Вы можете использовать встроенный сервер во время разработки, но вы должны использовать полный вариант развертывания для производственных приложений. (Не используйте встроенный сервер разработки в процессе производства.)

Рекомендуется

  • Прокси HTTP трафик через apache2 на флажок.

Таким образом, apache2 может обрабатывать все ваши статические файлы (что очень хорошо – намного лучше, чем сервер отладки, встроенный в Flask) и действует как обратный прокси для вашего динамического содержимого, передавая эти запросы в Flask.

Здесь ссылка в официальную документацию о настройке Flask с Apache + mod_wsgi.

Изменить 1 – Уточнение для @Djack

Прокси HTTP-трафик для Flask через apache2

Когда запрос поступает на сервер на порт 80 (HTTP) или порт 443 (HTTPS), веб-сервер, такой как Apache или Nginx, обрабатывает соединение запроса и выдает, что с ним делать. В нашем случае полученный запрос должен быть сконфигурирован для передачи через флажок в протоколе WSGI и обрабатываться кодом Python. Это “динамическая” часть.

обратный прокси для динамического содержимого

Есть несколько преимуществ для настройки вашего веб-сервера, как указано выше;

  • Прекращение SSL. Веб-сервер будет оптимизирован для обработки запросов HTTPS только с небольшой конфигурацией. Не “сворачивайте свой собственный” в Python, который, вероятно, очень небезопасен в сравнении.
  • Безопасность. Открытие порта в Интернете требует тщательного рассмотрения безопасности. Сервер разработки флэшей не предназначен для этого и может иметь открытые ошибки или проблемы безопасности по сравнению с веб-сервером, предназначенным для этой цели. Обратите внимание, что плохо настроенный веб-сервер также может быть небезопасным!
  • Обработка статических файлов. Встроенный веб-сервер Flask может обрабатывать статические файлы, однако это не рекомендуется; Nginx/Apache гораздо эффективнее обрабатывают статические файлы, такие как изображения, CSS, файлы Javascript и передают только “динамические” запросы (те, где контент часто считывается из базы данных или изменения содержимого), обрабатываемый кодом Python.
  • + больше. Это граничит с вопросом для этого вопроса. Если вы хотите получить дополнительную информацию, сделайте некоторые исследования в этой области.

Ответ №1

1- Остановить другие приложения, использующие порт 80.
2- запустить приложение с портом 80:

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

Ответ №2

Для внешнего видимого сервера, где вы не используете apache или другой веб-сервер, просто введите

flask run --host=0.0.0.0 --port=80

Ответ №3

Если вы используете следующее для изменения порта или хоста:

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

используйте следующий код для запуска сервера (мой главный вход для flask – app.py):

python app.py

Вместо того, чтобы использовать:

flask run

Ответ №4

Если вы хотите, чтобы ваше приложение было на том же порту, то есть port = 5000, то просто в своем терминале выполните эту команду:

fuser -k 5000/tcp

и затем запустите:

python app.py

Если вы хотите работать с указанным портом, например, если вы хотите работать с портом = 80, в основном файле просто укажите это:

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

Ответ №5

Ваша проблема в том, что у вас уже запущен веб-сервер apache, который уже использует порт 80. Таким образом, вы можете:

  • Убить apache: вы должны, вероятно, сделать это через /etc/init.d/apache2 stop, а не просто убивать их.

  • Разверните флеш-приложение в процессе apache, как описано фляжка в apache.

Ответ №6

Мне пришлось установить FLASK_RUN_PORT в моей среде на указанный номер порта. В следующий раз, когда вы запустите ваше приложение, Flask загрузит эту переменную среды с выбранным вами номером порта.

Ответ №7

Вам не нужно менять номер порта для своего приложения, просто настройте свой www-сервер (nginx или apache) на запросы прокси-сервера, чтобы порт флажка. Обратите внимание на uWSGI.

Ответ №8

установите порт с помощью app.run(port=80,debug=True) для debug необходимо установить значение true, если он включен

Ответ №9

Самое простое и лучшее решение

Сохраните ваш .py файл в папке. В этом случае моя папка называется test. В командной строке запустите следующее

c:test> set FLASK_APP=application.py
c:test> set FLASK_RUN_PORT=8000
c:test> flask run

—————– Следующее будет возвращено —————-

 * Serving Flask app "application.py"
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -

Теперь в вашем браузере введите: http://127.0.0.1:8000. Спасибо

Ответ №10

Я не могу запустить свое приложение на 80, оно запускается на 5000 просто отлично. Я не вижу, как работает Apache? что еще я могу проверить? Мы хотим работать на 80, поэтому мы можем использовать URL без указания порта.

>     server.run(debug=False, host=args.host, port=args.port)   File "/home/ryanicky/.local/lib/python3.6/site-packages/flask/app.py", line
> 944, in run
>     run_simple(host, port, self, **options)   File "/home/ryanicky/.local/lib/python3.6/site-packages/werkzeug/serving.py",
> line 1009, in run_simple
>     inner()   File "/home/ryanicky/.local/lib/python3.6/site-packages/werkzeug/serving.py",
> line 962, in inner
>     fd=fd,   File "/home/ryanicky/.local/lib/python3.6/site-packages/werkzeug/serving.py",
> line 805, in make_server
>     host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd   File
> "/home/ryanicky/.local/lib/python3.6/site-packages/werkzeug/serving.py",
> line 698, in __init__
>     HTTPServer.__init__(self, server_address, handler)   File "/usr/lib64/python3.6/socketserver.py", line 456, in __init__
>     self.server_bind()   File "/usr/lib64/python3.6/http/server.py", line 136, in server_bind
>     socketserver.TCPServer.server_bind(self)   File "/usr/lib64/python3.6/socketserver.py", line 470, in server_bind
>     self.socket.bind(self.server_address) OSError: [Errno 98] Address already in use [ryanicky@webstr WebSTR]$ systemctl status httpd Unit
> httpd.service could not be found.

If like me you’re obsessed with Python Flask, you might have asked yourself, “How on Earth do I run multiple Flask apps at the same time?!”.

It’s actually pretty simple!

What Happens at Default Settings

Before I get to the solution, I’ll first show you what happens if you leave everything at the default settings as it’s important to know.

For this test I’m running my Pay Calculator App and my Timezone List App together.

The app you launch first will always take priority. In this case, my Pay Calculator interface shows up on 127.0.0.1:5000. The interesting thing is that when I run the Timezone App, there’s no error. Python still launches a web server on 127.0.0.1:5000.

The catch is that all calls from my browser to localhost (127.0.0.1) are routed to the web server created by the Pay Calc app. If I try and browse to a web page that is unique to the Timezone App, I get a 404 error. The page doesn’t exist in the Pay Calc app and therefore the call fails.

As expected, the second I CTRL+C my Pay Calc app, everything springs to life for the Timezone app. Browsing to localhost brings up the Timezone interface and browsing to the aforementioned unique page works.

Specify a Port!

The solution? Specify a port number!

In Flask code, it’s the app.run() code that kicks everything off. Without that code, there’s no app.

By default, this starts the web server on 127.0.0.1:5000. We can change this!

if __name__ == "__main__":
    app.run(port=5001)

Believe it or not, it’s as simple as that!

Throw the port number you want to access the web app from to app.run() and the web server launches on that port. So simple and easy!

Conclusion and Discussion

This is as simple as it gets. There is however something else to discuss.

If you’re trying to run two or more concurrent web apps, it’s likely that you want these apps running in a sort of “production” environment. That is, you want them running all the time, it’s no longer just for a test.

That’s exactly my case. I want a few Flask apps running from my NAS on my local network at home.

The web server bundled in Flask is a development server. It may be fine for my home network but best practice mandates I use a dedicated web server like nginx.

Or another question, should I even use Flask for making production apps? Once I get to this level of production should I be moving to Django?

I’m actually not too sure! I’m definitely keen to hear everyone’s opinion on this. What do you use (if at all) for this sort of thing?

Do you use Flask for small apps and testing and Django for the bigger and badder stuff?

And as always, Keep Calm and Code in Python!

— Julian

Want a career as a Python Developer but not sure where to start?

Flask provides a run command to run the application with a development server. In
debug mode, this server provides an interactive debugger and will reload when code is
changed.

Warning

Do not use the development server when deploying to production. It
is intended for use only during local development. It is not
designed to be particularly efficient, stable, or secure.

See Deploying to Production for deployment options.

Command Line¶

The flask run CLI command is the recommended way to run the development server. Use
the --app option to point to your application, and the --debug option to enable
debug mode.

$ flask --app hello --debug run

This enables debug mode, including the interactive debugger and reloader, and then
starts the server on http://localhost:5000/. Use flask run --help to see the
available options, and Command Line Interface for detailed instructions about configuring and using
the CLI.

Address already in use¶

If another program is already using port 5000, you’ll see an OSError
when the server tries to start. It may have one of the following
messages:

  • OSError: [Errno 98] Address already in use

  • OSError: [WinError 10013] An attempt was made to access a socket
    in a way forbidden by its access permissions

Either identify and stop the other program, or use
flask run --port 5001 to pick a different port.

You can use netstat or lsof to identify what process id is using
a port, then use other operating system tools stop that process. The
following example shows that process id 6847 is using port 5000.

$ netstat -nlp | grep 5000
tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 6847/python

macOS Monterey and later automatically starts a service that uses port
5000. To disable the service, go to System Preferences, Sharing, and
disable “AirPlay Receiver”.

Deferred Errors on Reload¶

When using the flask run command with the reloader, the server will
continue to run even if you introduce syntax errors or other
initialization errors into the code. Accessing the site will show the
interactive debugger for the error, rather than crashing the server.

If a syntax error is already present when calling flask run, it will
fail immediately and show the traceback rather than waiting until the
site is accessed. This is intended to make errors more visible initially
while still allowing the server to handle errors on reload.

In Code¶

The development server can also be started from Python with the Flask.run()
method. This method takes arguments similar to the CLI options to control the server.
The main difference from the CLI command is that the server will crash if there are
errors when reloading. debug=True can be passed to enable debug mode.

Place the call in a main block, otherwise it will interfere when trying to import and
run the application with a production server later.

if __name__ == "__main__":
    app.run(debug=True)

So I followed this tutorial on-line and built a site that works perfectly on my local network. Now I’m trying to deploy it at Google’s App Engine and I’m encountering an error.
Basically I don’t know how to change the port my flask app is running on (without using app.run() ).

I just practially copy-pasted the code from the tutorial and adjusted it a bit, so I’m not sure how to set th eport withing the code. And since the tutorial never used any app.run(port=8080) and the page works, I’m not sure I want to introduce that slice of code. However, the code does use app.config[] to set the SECRET_KEY for example. And I’ve tried using the same method to set the PORT, but it just doesn’t work. How can do this??

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

#init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()


def create_app():
    app = Flask(__name__)
    app.config['PORT'] = 8080
    app.config['SECRET_KEY'] = b'someweirdshit'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

    #blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    #blueprint for non-auth parts of app
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

The code above is just one of the scripts used in my Flask App. I know it is being executed since the app succesfully connects and uses the db.sqlite databased configured in line 13. But line 11 (where I try to configure the port) just doesn’t seem to work.
Command Line Screenshot where Flask App is seen running on port 5000 and not 8080

So I followed this tutorial on-line and built a site that works perfectly on my local network. Now I’m trying to deploy it at Google’s App Engine and I’m encountering an error.
Basically I don’t know how to change the port my flask app is running on (without using app.run() ).

I just practially copy-pasted the code from the tutorial and adjusted it a bit, so I’m not sure how to set th eport withing the code. And since the tutorial never used any app.run(port=8080) and the page works, I’m not sure I want to introduce that slice of code. However, the code does use app.config[] to set the SECRET_KEY for example. And I’ve tried using the same method to set the PORT, but it just doesn’t work. How can do this??

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

#init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()


def create_app():
    app = Flask(__name__)
    app.config['PORT'] = 8080
    app.config['SECRET_KEY'] = b'someweirdshit'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))

    #blueprint for auth routes in our app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    #blueprint for non-auth parts of app
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

The code above is just one of the scripts used in my Flask App. I know it is being executed since the app succesfully connects and uses the db.sqlite databased configured in line 13. But line 11 (where I try to configure the port) just doesn’t seem to work.
Command Line Screenshot where Flask App is seen running on port 5000 and not 8080

Like this post? Please share to your friends:
  • Как изменить порт apache2
  • Как изменить порт apache windows
  • Как изменить порт 8291 winbox mikrotik
  • Как изменить порт 3389 на другой
  • Как изменить порог разряда батареи