I have designed a rest API with Flask now I want to create a simple web server in python to get and post data. How to create web server in python? I do not want to use curl and localserver 5000
For Linux
Open up a terminal and type:
$ cd /home/somedir
$ python -m SimpleHTTPServer
Now your http server will start in port 8000. You will get the message:
Serving HTTP on 0.0.0.0 port 8000 ...
Now open a browser and type the following address:
http://your_ip_address:8000
You can also access it via:
http://127.0.0.1:8000
or
http://localhost:8000
Also note:
If the directory has a file named index.html, that file will be served as the initial file. If there is no index.html, then the files in the directory will be listed.
If you wish to change the port that's used start the program via:
$ python -m SimpleHTTPServer 8080
change the port number to anything you want.
On python3 the command is python3 -m http.server
A Google search would easily lead you to this post
To create a simple HTTP webserver in python, use the in-built SimpleHTTPServer module as shown below:
python -m SimpleHTTPServer 8080
where 8080 is the port number.
For really simple options, as per the one-liners given. For something that can expand easily in the asyncio framework, this is not a bad start to serve files from the current folder (hence the os.path).
import asyncio
from aiohttp import web
from os.path import abspath, dirname, join
async def main():
app = web.Application()
app.add_routes([
web.static('/', abspath(join(dirname(__file__))))
])
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, 'localhost', '8080').start()
await asyncio.get_running_loop().create_future()
asyncio.run(main())
Related
I work on a linux cluster that is behind a firewall. It does not have web access.
I had this idea I could try to run flask and direct it to a port I know is open (5901 for vnc), and then tunnel that port and view it in my browser.
It's not working so far. Is this possible at all?
Here is what I'm doing:
helloflask.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5901)
#app.run()
I run python helloflask.py then
ssh -L 5901:<inner server>:5901 <outer server>
Then I navigate to localhost:5901. Nothing. I also tried links localhost:5901 and links <server>:5901, but again nothing.
Is it possible there is some way to do this?
You can do this :
Run your flask app or notebook on the remote server on any port. Say for example port 5000.
On your local machine run below command to establish the ssh tunnelling :
ssh -D 8123 -f -C -q -N username#remotesrrver
The port 8123 is arbitrary here it can be any allowed port on your local machine. Then setup one of your browser (Fire fox may be) to use socks proxy on port 8123
Make sure that the traffic is proxied for localhost also. By default Firefox disable proxying for localhost. Once these are established you should be able to go to http://localhost:5000 on your browser to hit the app /notebook running on the remote machine
And your hellowflask.py should be like something below for it to work
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5901)
#app.run()
Might I suggest trying something like pyngrok to programmatically manage an ngrok tunnel for you? Full disclosure, I am the developer of it. Flask example here, but it's as easy as installing pyngrok:
pip install pyngrok
and using it:
from pyngrok import ngrok
# <NgrokTunnel: "http://<public_sub>.ngrok.io" -> "http://localhost:5000">
http_url = ngrok.connect(5000)
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
I found a MediaCrush open source from here
https://github.com/MediaCrush/MediaCrush
But stuck in last steps.
I started the Redis server, use command
$redis-cli
that received the "PONG" response.
Then used the command
$celery worker -A mediacrush -Q celery,priority
and after
python app.py
But it seem that nothing works. I just installed nginx, run it on my IP ok, but after edit the nginx.conf like a Mediacrush script, then accessing my IP, nothing happens.
So what am I missing here? and how to config nginx server and start redis server to run this script on CentOS (i can change it to Arch like them if required)
Thanks!
I just wanted to run it for fun.. so this may be wrong but what I did after running the celery daemon was edit the app.py script and manually set the host, port, and set debug to false. Then I just executed it like any other python script.
EDIT: This may work
PORT=8000 gunicorn -w 4 app:app
it switches your port to 8000 and runs the gunicron daemon with 4 workers. both approaches worked for me.
Edit File: ./app.py
from mediacrush.app import app
from mediacrush.config import _cfg, _cfgi
import os
app.static_folder = os.path.join(os.getcwd(), "static")
if __name__ == '__main__':
# CHANGE THIS LINE TO REFLECT YOUR DATA
app.run(host=_cfg("debug-host"), port=_cfgi('debug-port'), debug=True)
# FOR EXAMPLE I CHANGED IT TO THIS
# app.run(host="92.222.25.245", port=8000, debug=0)
Also to start redis i believe you should do redis-server& I use the cli to manually tinker with it.
Btw I did this on linux mint / ubuntu 14.04 / debian
I am trying to teach myself Flask in a Vagrant environment. I understand that Flask runs a server on port 5000 by default. In my Vagrantfile I have:
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.network :forwarded_port, guest: 5000, host: 5000
I have a simple tutorial Flask app:
from flask import Flask
app = Flask(__name__)
#app.route('/hello')
def hello_world():
return 'Hello world!'
if __name__ == '__main__':
app.run(debug=True)
Yet when I run python hello.py in my Vagrant environment and subsequently go to 127.0.0.1:5000/hello in Chrome on my desktop, I can't connect.
I don't know nearly enough about networking. What am I missing?
If you are accessing from Chrome in your desktop, you are technically accessing from a different computer (hence you need to place host='0.0.0.0' as argument to app.run() to tell the guest OS to accept connections from all public (external) IPs.
This is what worked for me (for both 127.0.0.1:5000/hello and localhost:5000/hello in Chrome):
from flask import Flask
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0')
You possibly need to get Flask to serve on an externally-visible URL: see the docs
This may be caused by Vagrant (VirtualBox) NAT Port forwarding not working properly (port conflicts).
To narrow down the issue, you may want to make sure that port 5000 is open correctly on both end, this can be done by using nmap, nc (netcat) or netstat etc.
e.g. on host
nmap 127.0.0.1
nc -vz 127.0.0.1 5000
curl http://127.0.0.1:5000
Within the guest
nmap GUEST_IP
nc -vz GUEST_IP 5000
curl http://GUEST_IP:5000
NOTE: GUEST_IP is most likely in the 10.0.2.0/24 network (vbox NAT engine default).
Running these commands on both your host and within the VM (guest box) will tell you if the ports are open.
Make sure your python hello world binds NOT ONLY to the loopback device so that it can serve requests from external clients.
Use lsof -i :5000 or netstat -nap | grep :5000 to determine which program is binding the port for further troubleshooting.
Do you have curl installed in your vagrant box? If not install it and try curl http://127.0.0.1:5000/hello. If you get a response and you see Hello world! in your console, then on flask side everything is fine. Back to the virtual box - When you open the network settings, from what you said above, I assume you are using a NAT address. In that case you will need to set the host address to 127.0.0.1, port 5000, leave the guest address empty and put port 5000 again and that should do the trick(port forwarding). One thing I've noticed about vagrant in those situations is that it works best if you use virtualhosts. Take a look here.
I was using Vagrant and solved it by adding this line of code to Vagrantfile:
config.vm.network "forwarded_port", guest: 5000, host: 5000, host_ip: "127.0.0.1"
make sure to 'vagrant reload' after you change your Vagrantfile
I'm running Python 3.2 on Windows. I want to run a simple CGI server on my machine for testing purposes. Here's what I've done so far:
I created a python program with the following code:
import http.server
import socketserver
PORT = 8000
Handler = http.server.CGIHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
In the same folder, I created "index.html", a simple HTML file. I then ran the program and went to http://localhost:8000/ in my web browser, and the page displayed successfully. Next I made a file called "hello.py" in the same directory, with the following code:
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print()
print("""<html><body><p>Hello World!</p></body></html>""")
Now if I go to http://localhost:8000/hello.py, my web browser displays the full code above instead of just "Hello World!". How do I make python execute the CGI code before serving it?
Take a look at the docs for CGIHTTPRequestHandler, which describe how it works out which files are CGI scripts.
Though not officialy deprecated, the cgi module is a bit clunky to use; most folks these days are using something else (anything else!)
You can, for instance, use the wsgi interface to write your scripts in a way that can be easily and efficiently served in many http servers. To get you started, you can even use the builtin wsgiref handler.
def application(environ, start_response):
start_response([('content-type', 'text/html;charset=utf-8')])
return ['<html><body><p>Hello World!</p></body></html>'.encode('utf-8')]
And to serve it (possibly in the same file):
import wsgiref.simple_server
server = wsgiref.simple_server.make_server('', 8000, application)
server.serve_forever()
simplest way to start a cgi server for development is following:
create a base directory with all your html and other files
create a subdirectory named cgi-bin with all your cgi files
cd to the base directory
run python -m http.server --cgi -b 127.0.0.1 8000
Now you can connect to http://localhost:8000 and tst your html code with cgi scripts