How to set the DocumentRoot while using python's HTTPServer? - python

I have the following code as my python server:
#!/usr/bin/python3
from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8080
host_name = "localhost"
httpd = HTTPServer((host_name, port), CGIHTTPRequestHandler)
print("server started, to quit press <ctrl-c>")
httpd.serve_forever()
How do you set the DocumentRoot to which the server is serving the pages from.

The built-in CGIHTTPRequestHandler class serves from the current working directory, which is normally the directory from which you invoked Python.
This class is used to serve either files or output of CGI scripts from the current directory and below.
You can use os.chdir() to change the current working directory.

When you handle the GET request, you need to translate that into a path relative to the current directory the script is running in.
Look at http://docs.python.org/library/simplehttpserver.html#module-SimpleHTTPServer and the do_GET section. You should be able to adapt that for your purposes

Related

Trying to make a simple python web server and its not starting

Ive been trying to make a web server and I have the code down that should be able to get it running but when I go in to the Command Prompt and type python app.py it doesn't run when it should this is the code that I have
from flask import Flask
app = Flask(__name__)
#app.route("/")
def main():
return "Welcome to my Flask page"
if __name__ == "__main__":
app.run(debug = True, host = "0.0.0.0", port=80)```
The server won't run on port 80, it will run on the default port (5000). If you run the server and navigate to HTTP://0.0.0.0:5000/, you should see your / response. See Why can't I change the host and port that my Flask app runs on?.
To change the port Flask runs on, you can specify it in the command line:
flask run -h localhost -p 3000
Here, I run the server on localhost:3000. If you try to run the server on port 80, you will get a permission denied error since any port under 1024 needs root privileges (as m1ghtfr3e said in their answer).
Also, this is a great tutorial I recommend to anyone learning flask https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I think the problem is port 80.
Which OS are you using?
Ports under 1024 need root privileges, there is also a possibility that it is not working because some other service (like Apache) is running on this port.
So either fixing privileges or services or changing the port should make it run.

FastAPI/uvicorn not working when specifying host

I'm running a FastAPI app in Python using uvicorn on a Windows machine. It works fine when I do any one of the following options:
Run the following code on my mac, or
When I don't specify the port for uvicorn (remove the host parameter from the uvicorn.run call)
When I specify port '127.0.0.1', which is the host it uses when I don't specify a host at all.
from fastapi import FastAPI
import uvicorn
app = FastAPI()
#app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == '__main__':
uvicorn.run(app, port=8080, host='0.0.0.0')
When I go to 0.0.0.0:8080 on my browser, I get an error that says "This site can’t be reached".
I have checked my current active ports to make sure I'm not getting a collision using netstat -ao |find /i "listening" and 0.0.0.0:8080 is not in use.
My current file configuration looks like this:
working_directory
└── app
├── gunicorn_conf.py
└── main.py
My gunicorn_conf.py is super simple and just tries to set the host and port:
host = "0.0.0.0"
port = "8080"
How can I get this to work when I specify host '0.0.0.0'?
As I was writing the question above, I found the solution and thought I would share in case someone else runs into this. To get it to work put "http://localhost:8080" into the web browser instead of "http://0.0.0.0:8080" and it will work fine. This also works if you're hitting the endpoint via the python requests package, etc.
Run this in terminal uvicorn main:app --port 8086 --reload

Flask App visible to localhost only

Trying to host python flask app on Ubuntu 18.04 vps. I am using python version 3.6 and not using virtual environment since that vps will be used to host one app only.
This is the content of apache2 config file for this app:
<VirtualHost *:80>
ServerName 15.16.541.21
WSGIScriptAlias / /var/www/psoftware-nis-app/Backend/flask-api/api.wsgi
<Directory /var/www/psoftware-nis-app/Backend/flask-api>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
Static IP address I provided is of course not real, but in conf it is the real static IP address of the machine that hosts this app.
When I curl http://localhost/api/test_endpoint I get a valid response (from vps).
But when I curl http://15.16.541.21/api/test_endpoint from my laptop I get:
Connection timed out
When I execute this: nmap -p 80 15.16.541.21 i get:
Host seems down. If it is really up, but blocking our ping probes,
try -Pn
So when i add -Pn and execute: nmap -p 80 18.191.182.118 -Pn I get:
Host is up. PORT STATE SERVICE 80/tcp filtered http
Is something wrong with my config file? Or any other idea why the app is not visible to outside world?
EDIT:
I have configured main python module, host option is set:
if __name__ == '__main__':
app.run(host='0.0.0.0')
By default, flask app is only visible for local access. You need to specify the host option --host=0.0.0.0 to make it visible for other network.
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 the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
--host=0.0.0.0 to the command line:
flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.
Check this http://flask.pocoo.org/docs/1.0/quickstart/#quickstart

Vagrant, Flask — App not running on 10.10.10.10, 127.0.0.1

I'm running an app on my local box via Vagrant. The Python/Flask app launches and prints:
* Running on http://127.0.0.1:5000/
* Restarting with reloader
I found this https://github.com/makersquare/student-dev-box/wiki/Using-Vagrant-for-Development#testing-web-based-applications-in-vagrant
which suggests that Vagrant apps run on 10.10.10.10 (not 127.0.0.1), but when I navigate to that IP address (port 5000), I get the same result: "This webpage is not available".
Question: my app is running, but on what IP address? I can't seem to find it. Do I need to modify some configuration files?
Thanks in advance.
There are many ways how you could run flask web app on virtual machine (managed by vagrant). I think that following approach is quite flexible, because you don't have to deal with different ip address. Also it looks like you are developing on a host machine.
There are 2 things you need to configure. In VagranFile, you need configure port forwarding.
Vagrant.configure(2) do |config|
# use default box
config.vm.box = "ubuntu/trusty64"
# forward port guest machine:5000 -> host machine:5000
# port 5000 is default for flask web app
config.vm.network "forwarded_port", guest: 5000, host: 5000
end
Then, on virtual machine, you should start flask app on ip 0.0.0.0 which means that web app will serve for any IP address. More on this topic -> flask doc section Externally Visible Server
if __name__ == "__main__":
app.run("0.0.0.0", debug=True)
That's it. You should be able to connect to http://localhost:5000
In the file where you call app.run, it should be
app.run(host='0.0.0.0', port=...
In the host OS, navigate to the IP of the guest with the port that you're running the app from.
sjudǝʊ is right but it took me 4 hours to figure out he forgot to mention you also must run:
vagrant halt and then vagrant up
in order for your update to the vagrant file to actually take affect
In the latest version of Flask and python you do not need to configure vagrant file or no change required in the python script. Just run the flask with --host
flask run --host=192.168.10.80

Serving Python scripts with CGIHTTPServer on Mac OS X

I'm trying to set up Python's CGIHTTPServer on Mac OS X to be able to serve CGI scripts locally, but I seem to be unable to do this.
I've got a simple test script:
#!/usr/bin/env python
import cgi
cgi.test()
It has permissions -rwxr-xr-x# and is located in ~/WWW (with permissions drwxr-xr-x). It runs just fine from the shell and I have this script to serve them using CGIHTTPServer:
import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["~/WWW"]
PORT = 8000
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
But when I run it, going to localhost:8000 just serves the content of the script, not the result (i.e. it gives back the code, not the output).
What am I doing wrong?
The paths in cgi_directories are matched against the path part of the URL, not the actual filesystem path. Setting it to ["/"] or [""] will probably work better.

Categories