Getting python scripts to run in http simple server - python

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.

Related

Flutter Web and logging on iPhone

I have a Flutter Web app with an iOS Safari-specific error. To debug it I create a build (flutter build web) and run Python's http.server (python3 -m http.server), then use ngrok to be able to open the app on my mobile device.
To be able to see logs I use OverlayEntry with Text, but it's not very convenient.
Python's http.server does some logging that looks like this:
Serving HTTP on :: port 8000 (http://[::]:8000/) ...
::1 - - [10/Sep/2022 20:05:06] "GET / HTTP/1.1" 200 -
::1 - - [10/Sep/2022 20:05:07] "GET /flutter.js HTTP/1.1" 304 -
Is it possible to log something from a Flutter app to see it inside Python's http.server logs?
Yes, it's possible. You can use print() to log something to the console. You can also use the dart:developer package to log to the browser's console. Example:
import 'dart:developer' as developer;
developer.log('Hello world!', name: 'my.app.category');

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

Can't get even a simple uwsgi test to work

I'm trying to get nginx/django/uwsgi set up, and I'm stuck at the first step. I'm just trying to get uwsgi to serve a test application directly to my browser, as described here as a basic test.
So, I create the test.py file:
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]
And then I start it up with $ uwsgi --plugins python --http :8001 --wsgi-file test.py
The output appears to be OK. I get the message WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x3a14c8 pid: 8295 (default app). I would expect that I would then be able to aim my browser at 127.0.0.1:8001, and see a hello world message. However, chrome just tells me that the site can't be reached.
I've been trying various permutations of tests from all over the internet for a solid day, but this is the simplest test I've found, and no one mentions what to do if it fails.
For reference, I'm using uwsgi 2.0.15 and python 3.6.1 on Arch.
EDIT: Evidently someone thought my question "did not show any research effort." So, to summarize what I've tried:
I checked that iptables wasn't blocking anything
I tried it on various ports
I tried moving on with the tutorial to see if it works with a real django project
I tried doing this all in a virtualenv
I tried running from a uwsgi ini file instead of the command line
I tried starting over any using various other tutorials.
Read this post and tried the answer
Output of $ curl -v 127.0.0.1:8001:
* Rebuilt URL to: 127.0.0.1:8001/
* Trying 127.0.0.1...
* TCP_NODELAY set
* connect to 127.0.0.1 port 8001 failed: Connection refused
* Failed to connect to 127.0.0.1 port 8001: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 127.0.0.1 port 8001: Connection refused
Please let me know if you can think of anything else.

Customizing Django's server configurations

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.

How do I set up a Python CGI server?

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

Categories

Resources