How do I set up a Python CGI server? - python

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

Related

Python import from a virtual environment when run in apache

I am new in python. I am trying to deploy python code on apache server for i.e i have created flask api. So for apache i have installed XAMPP and changed my httpd.conf to execute python on apache. It works well!! Here is code example which is working
Code working:
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
print("Content-type: text/html\n")
print ("Hello Python Web Browser!! This is cool!!")
But when I tried to import that through 500 Error, Here is the code
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'testing'
if __name__ == '__main__':
app.run(debug = True)
flask is installed on my environment (myproject). When I run through command like python test.py and it works.
Flask has it's own development web server.
Using python myfile.py which will work properly as a webserver (no need for apache on development).
If you still want do deploy on Apache, Flask have some info on how to do so, docs: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/
Special attention to this: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/#creating-a-wsgi-file

How to create a simple HTTP webserver in python?

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())

Getting python scripts to run in http simple server

I have a simple python script that I want to serve as a website:
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
I'm in that folder and run
$ python3 -m http.server
then I visit
http://hassbian.local:8000/song.py
The terminal says this and I get the file as a txt file, the script won't execute.
Serving HTTP on 0.0.0.0 port 8000 ...
192.168.1.115 - - [04/Jun/2017 14:19:59] "GET / HTTP/1.1" 200 -
192.168.1.115 - - [04/Jun/2017 14:20:04] "GET /song.py HTTP/1.1" 200 -
Running on a rasberry pi
SimpleHTTPServer doesn't do CGI. If you want CGI you will have to use CGIHTTPServer
This module can run CGI scripts on Unix and Windows systems.
I am not sure if that's what you really want, but invoking a python script in the manner you have shown is CGI. CGI is a really old way of doing things. Running simple web apps with python is now almost exclusively the domain of webapp2 or flask. While more complex apps involving databases are dominated by django.

Deploying flask app to Apache shared hosting

I am trying to deploy a simple flask application in the Apache shared hosting server.
I am not sure what is wrong here.
I am stuck at the .cgi file for now.
The flask app - hello.py:
#!/usr/bin/python
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!\n"
if __name__ == "__main__":
app.run()
The myapp.cgi file:
#!/usr/bin/python
import os
from wsgiref.handlers import CGIHandler
from hello import app
os.environ['SERVER_NAME'] = '127.0.0.1'
os.environ['SERVER_PORT'] = '5000'
os.environ['REQUEST_METHOD'] = 'GET'
os.environ['PATH_INFO'] = ""
CGIHandler().run(app)
Both the files are placed in the /home/username/public_html/cgi-bin directory
The same cgi-bin has the directory named myenv - it's a virtualenv I have created. The virtualenv is active.
Now,
I navigate to the cgi-bin directory and run -
python hello.py
I get this :
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
So this is fine. Now I am running the myapp.cgi file:
python myapp.cgi
I get this :
Status: 301 MOVED PERMANENTLY
Content-Type: text/html; charset=utf-8
Content-Length: 251
Location: http://127.0.0.1:5000/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: http://127.0.0.1:5000/. If not click the link.
How can I make this status as 200 OK,
Please suggest.
Thanks!
I had to make few changes in the .cgi file. Below is the final file.
import os
from wsgiref.handlers import CGIHandler
from hello import app
CGIHandler().run(app)
and added these lines in my hello.py file:
import os
import sys
sys.path.insert(0, '/home/username/public_html/cgi-bin/myenv/lib/python2.6/site-packages')
Refer this - https://medium.com/#mohdejazsiddiqui/deploy-flask-app-in-apache-shared-hosting-5b3c82c8fd5e
I think you have 2 big misunderstandings about how apache works with flask with the help of cgi.
Apache uses the system directorys for the python interpreter. You can in fact change the sys.path Like here descriped. But that is far from ideal.
you don't have to call python for your cgi file. The Server will do that when you did your config correctly
in the cgi doc of flask are some ways how you get the server to work with the cgi file.
Since you say you want it to upload at shared hosting writing a .htaccess file for your needs would be the most promesing way, since most of those services only allow you to work from your public dircectory. In this case you also have to use a shared hoster where python is on the server or be willed to install python with all the packages you need for you, since you can't install any packages by yourself.
You could try the changing of the interpreter path, but i have no experience if that would work on shared hosting.

How to start redis server and config nginx to run mediacrush script on CentOS?

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

Categories

Resources