user manager.py runserver my flask webframework can start on http://127.0.0.1:5000 but it can not access on other computer in network.
so i need use an open IP in network.
although i use bellow command:
manage.py runserver 192.168.49.25:8000
it can not run and give a error info:
manage.py: error: unrecognized arguments: 192.168.49.25:8000
I don't known what's wrong with it??
If you want to use Flask-Script (python manage.py runserver) to run your Flask Application you can use the parameter --host to run it on a public IP.
python manage.py runserver --host 0.0.0.0
see also: https://flask-runner.readthedocs.org/en/latest/
Read the documentation:
Externally Visible Server If you run the server you will notice that
the server is only accessible from your own computer, not from any
other in the network. This is the default because in debugging mode a
user of the application can execute arbitrary Python code on your
computer.
If you have debug disabled or trust the users on your network, you can
make the server publicly available simply by changing the call of the
run() method to look like this:
app.run(host='0.0.0.0') This tells your operating system to listen on
all public IPs.
If you're already using Flask-Script then you have a way to get your host defined in your code.
from yourapp import create_app
from flask_script import Manager, Server
from yourapp import config
app = create_app(config.DevelopmentConfig)
manager = Manager(app)
manager.add_command("runserver", Server(host=app.config['HOST'], port=app.config['PORT']))
if __name__ == '__main__':
manager.run()
now the server host and port will come from config
Related
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
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
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
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.
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
You can use this 2 environmental variables:
set FLASK_RUN_HOST=0.0.0.0
set FLASK_RUN_PORT=3000
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
I am able to run a webserver using the following code
from flask import Flask
from waitress import serve
app = Flask(__name__, static_url_path='/static')
...
serve(app, port=8080)
The problem is that I can access it only from the machine where it is running, if I try to access it using the ipv4 ip, it doesn't work. Am I missing a step?
Simple example,try it!
I hope it will help you.
app1.py
from flask import Flask
app = Flask(__name__)
# app.run(host='0.0.0.0', port=8080,debug=True)
waitress_server.py
from waitress import serve
import app1
serve(app1.app, host='0.0.0.0', port=8080)
Then run below command
python waitress_server.py
Waitress now provides a simple command line Utility called waitress-serve for running the Flask Application. Please note that this answer is valid for Waitress 1.30. The command line arguments could change in future.
If your Flask application is called myapplication and the method which instantiates your application is called create_app, then you can run the command below. This will launch the server listening on port 8080 by default.
waitress-serve --call "myapplication:create_app"
If you wish to launch it on port 80 (http), then all you need to do is:
waitress-serve --port=80 --call "myapplication:create_app"
D:\flaskapps>waitress-serve --port 80 --call "dlrlsummarizer:create_app"
Serving on http://ADITHYA-PC:80
Waitress serve command line arguments.
Flask 1.0 production deployment tutorial.
Try using
serve(app, host='0.0.0.0', port=8080)
I ran into this question and looking something similar.
After looking at the documentation and combined with your original request, I tested
serve(app, port=8080, host="x.x.x.x")
Where x.x.x.x is my host ip address.
It works fine on my end.
Complete code
from flask import Flask
from waitress import serve
app = Flask(__name__)
...
serve(app, port=8080, host="x.x.x.x")
I realize this question was probably based in a miss-diagnosed firewall or NAT issue, but in case people come here actually wanting to serve a Flask app with waitress on windows properly (as a service), I want to point to my answer here, so that it can be of use and receive some feedback.
from flask import Flask
from waitress import serve
app = Flask(__name__)
#app.route("/")
def hello_world():
return "<p>Hello stay healthy.</p>"
if __name__ == "__main__":
serve(app, host="127.0.0.1", port=8080)
Problem may persist in host. You can use host="127.0.0.1" in your program.
Save your program in app.py file.
Run your program.
The server will be accessible at http://localhost:8080
I just realized that can be reached by computers in the same network, but not from computers outside of the network
You need to forward the port in your router and use your public IP address.
To be able to use your internal PC (behind the router) you need to forward in the router the externl port 8080 to internal port 8080 and IP address of your server.
In this conditions you can access your server from outside your network using your external IP. That is OK if you have a static IP address allocated by your provider. If not than you can use a free DNS provider (I use DnsExit) which will provide you with a name for your external IP address. This way you can access your server with a name even if the IP address from your service provider changes from time to time.
After we installed the Django, we use the command:
python manage.py runserver
we can run a server, but I don't know the server is which server, and I searched the django directory, find the server is not in the directory:
aircraftdeMacBook-Pro:Django-1.11.2-py2.7.egg ldl$ cd django/
aircraftdeMacBook-Pro:django ldl$ ls
__init__.py bin dispatch shortcuts.pyc utils
__init__.pyc conf forms template views
__main__.py contrib http templatetags
__main__.pyc core middleware test
apps db shortcuts.py urls
So, I have two questions:
The server is which web-server, and how can I find its location?
If we finish the application, if we use the web-server as the python-web's web-server(means why not apache or nginx)?
The port default is 8000, how to change to the 80?
1) Django provides a default wsgi server as #sach20 mentioned.
2) The django server should be used for development. I personally use nginx and gunicorn to run my server. You can find a tutorial on how to set on up here:
Tutorial
3) You can run:
python manage.py runserver 0.0.0.0:80
You can substitute 80 with any port you want to use.
Django runserver is a local dev server, should not be used in production... APACHE AND NGINX are different things.
Django provides a simple WSGI server as a dev server.
Also id guess you have not looked inside the django docs because what you are looking for is right here
Examples of using different ports and addresses¶
Port 8000 on IP address 127.0.0.1:
django-admin runserver Port 8000 on IP address 1.2.3.4:
django-admin runserver 1.2.3.4:8000 Port 7000 on IP address 127.0.0.1:
django-admin runserver 7000
Django provides a default wsgi development server
My use case:
We need to run a watir-webdriver script in headless mode and our dev machines run Windows.
The gist of our problem:
I can stand up the python server inside the container, but I can't connect to it at its expected location from the host: http://192.168.59.103:8084.
The architecture:
A ruby script that "does something useful and prints the output to the console" and a basic python server that imports os and then executes os.system('ruby ourrubyscript.rb') inside our index route. We also brought in flask for api routing and flask.cors to eliminate potential cross origin issues.
Local test (on Host):
running "python server.py" in our host workspace stands up a python server on port 5000. Routing to it from a browser executes our route and prints the expected output to the console.
server.py
from flask import Flask
from flask import request
from flask.ext.cors import CORS
import os
app = Flask(__name__)
CORS(app, resources={r'/': {"origins": "*"}}, headers='Content-Type')
app.config['CORS_HEADERS'] = 'Content-Type'
#app.route('/')
def index():
return "<h1>Hello Stupid</h1>"
#app.route('/ruby/test', methods=['GET'])
def runRubyScript():
return os.system("ruby script.rb")
if __name__ == "__main__":
app.run()
When I nav to localhost:5000, "Hello Stupid" prints to my screen.
When I route to localhost:5000/ruby/test, our script runs and that script prints to my console.
Procedure to move this to docker
We pulled latest centos and installed wget, xvfb, git, ruby, python, pip, flask, flask-cors, and firefox; committed that to a local image named "webdev."
Then gem installed headless and installed phantomjs to $PATH
We then cloned our src repository to "/opt/testapp" in the container. This repository contains our "server.py" file and a "script.rb" file.
docker#boot2docker:~$ docker run -d -p 5000:5000 --name wd webdev python /opt/testapp/server.py
So, I left my boot2docker-vm bound to private ip 192.168.59.103, and I can confirm that this ip is valid by navigating to a different port that is running a different container; however, when I navigate to 5000, I get an ERR_CONNECTION_REFUSED. I had an almost "AHA!!" moment thinking that iptables had the port locked down by default and we needed to go open internal port 5000 in order to map it out to the vm but then I found that the centos image does not have iptables (or firewalld since this is CentOS7) installed by default. When that approach turned out to be incorrect, I decided to post to see if anyone might be able to assist here because I am out of ideas.
So I have figured out why this is not exposed to the host environment and this makes perfect sense.
In NAT mode, the virtual machine gets assigned a private static ip address: 192.168.59.103 (that is...the virtual machine gets assigned that IP)
Each container stands up with 2 adapters: a loopback and an externally facing virtual private bridge accessible to the vm.
When I stand up my server on port 5000, it binds directly to loopback inside the container and is inaccessible to the virtual machine.
Removing the localhost binding from the service and allowing it to
bind to the default gateway 0.0.0.0:5000
causes the service to listen on all adapters and allows communications
between the vm and the container's external adapter through the
virtual private bridge that gets created when the container stands.
For some reason, switching my virtual machine to run in Bridged mode against my NIC is causing the boot2docker-vm to crash on start....so I'm relegated to NAT for the time being until I can figure out how to switch it properly.
[Edit 1 (related to bridging)]
Bridge mode seems to currently be unsupported in boot2docker as of at least October 8, 2014. b2d expects a NAT adapter for ssh bootstrapping and the host adapter for container<->container socket access.
The current, unsupported, undocumented workaround to expose a container to hosts on a network is to add a third network interface to VirtualBox and bridge with it.
[Edit 2 (example server running against default gateway)]
Here is an example of a flask server that attaches to all interfaces:
Note that the only Δ between the server above and the server below is the final line of the configuration.
app.run()
needs to become
app.run(host='0.0.0.0')
from flask import Flask
from flask import request
from flask.ext.cors import CORS
import os
app = Flask(__name__)
CORS(app, resources={r'/': {"origins": "*"}}, headers='Content-Type')
app.config['CORS_HEADERS'] = 'Content-Type'
#app.route('/')
def index():
return "<h1>Hello Stupid</h1>"
#app.route('/ruby/test', methods=['GET'])
def runRubyScript():
return os.system("ruby script.rb")
if __name__ == "__main__":
app.run(host='0.0.0.0')
On firing up python's development server: >$ python manage.py runserver, by default it provides a default IP address and such, with the output:
>$ python manage.py runserver
Validating models...
0 errors found
February 12, 2014 - 23:20:35
Django version 1.6.2, using settings 'counter.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
How do I provide my own settings for an HTTP server? I want to specify my own port, ip address, as well as my own request handler. I added the following code in my models.py file, but it doesn't seem to be running. No print statements are being shown. My code is below:
def run():
print "starting run"
port = 8080
server_address = ('127.0.0.1', port)
httpd = HTTPServer (server_address, Counter_HTTPRequestHandler)
httpd.server_forever()
assert False # unreachab;e
if __name__ == '__main__':
run()
Am I supposed to provide this code somewhere else? I understand I can specify my own IP and PORT as arguments to runserver, but how I do execute my main - run() method so that I can specify my custom http request handler?
runverver takes port as an argument, run it as manage.py runserver 8080 to run on 8080
For more complex requirements, you might want to try something like uwsgi.
None of your print statements added in models.py work because when you runserver, you don't run models.py, you just import models from it.