Python from within Python - python

I'm trying to launch a simple server from a Python script:
server = Popen(['python' ,'-m', 'SimpleHTTPServer', '9090'], stderr=STDOUT, stdout=PIPE)
output = server.communicate()[0] # <- DEBUG
Reading the output, I see:
'/usr/bin/python: Import by filename is not supported.'
What's the problem? How to solve it?

I suggest change to code to this:
import SimpleHTTPServer
import SocketServer
PORT = 9090
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()

Related

Can't print (to printer) from Python when in a web server

I'm able to use this code to send a job to my system printer:
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE, close_fds=True)
print('printing from shell!')
lpr.stdin.write(b'print from python')
print('printed!')
However, if I use this code in a webserver, the code runs but the printer doesn't print.
import http.server
import socketserver
import subprocess
def print_out(a,b,c):
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE, close_fds=True)
print('printing from shell!')
lpr.stdin.write(b'print from python')
print('printed!')
PORT = 8080
with socketserver.TCPServer(("", PORT), print_out) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
This is true even if I try calling print_out() before creating the server (i.e., above PORT = 8080).
How can I make this work?

Python SimpleHttpServer, how to return files without extensions with plain/text mime type?

I coded following simple http server in python, I have some files without an extension and want to serve them with "text/plain" mime type. How can I achieve it?
import SimpleHTTPServer
import SocketServer
PORT = 80
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
pass
Handler.extensions_map['.shtml'] = 'text/html'
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
According to the module's source code this should work:
Handler.extensions_map[''] = 'text/plain'

How to get client IP from SimpleHTTPServer

Building a simple file server using the SimpleHTTPServer module in Python, however I'm running into issues when trying to get the IP from a connecting client. Here is what I have..
import SimpleHTTPServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", 8080), Handler)
print "Serving local directory"
while True:
httpd.handle_request()
print Handler.client_address[0]
When a client connects I get..
AttributeError: class SimpleHTTPRequestHandler has no attribute 'client_address'
I know this is because I haven't instantiated the class yet, but is there another way to get the IP from the client without having to create a handler instance? The client's IP is outputted to the console when a connection is made, I just need a way to grab that IP within my script.
Thanks!
Indeed, the Handler class object is unrelated to specific instances. Set up your own handler class, like this:
import SimpleHTTPServer
import SocketServer
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def handle_one_request(self):
print(self.client_address[0])
return SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
print("Serving local directory")
httpd = SocketServer.TCPServer(("", 8080), MyHandler)
while True:
httpd.handle_request()

Save logs - SimpleHTTPServer

How can I save the output from the console like
"192.168.1.1 - - [18/Aug/2014 12:05:59] code 404, message File not found"
to a file?
Here is the code:
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
BaseHTTPRequestHandler.log_message() prints all log messages by writing to sys.stderr. You have two choices:
1) Continue using BaseHTTPRequestHandler.log_message(), but change the value of sys.stderr:
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
import sys
buffer = 1
sys.stderr = open('logfile.txt', 'w', buffer)
httpd.serve_forever()
2) Create a new xxxRequestHandler class, replacing .log_message():
import SimpleHTTPServer
import SocketServer
import sys
PORT = 1548
class MyHTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
buffer = 1
log_file = open('logfile.txt', 'w', buffer)
def log_message(self, format, *args):
self.log_file.write("%s - - [%s] %s\n" %
(self.client_address[0],
self.log_date_time_string(),
format%args))
Handler = MyHTTPHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
I have used BaseHTTPServer instead of SimpleHTTPServer.
There you go:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 5451
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
#self.send_header('Content-type','text/html')
self.end_headers()
text_file = open("ip.txt", "a")
text_file.write(str(self.client_address) + "\n")
text_file.close()
# Send the html message
#self.wfile.write("Hello World !")
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()

Why using import BaseHTTPServer in Python?

This is the code I got from Tutorial of how to make local server by using python script to run in Terminal
import SimpleHTTPServer
import SocketServer
import BaseHTTPServer
import os
HOSTNAME = "localhost"
PORT = 8000
HANDLER = SimpleHTTPServer.SimpleHTTPRequestHandler
os.chdir("/Users/Team/Desktop/python server")
httpd = SocketServer.TCPServer((HOSTNAME, PORT), HANDLER)
print "serving at port", PORT
httpd.serve_forever()
I wonder why they have to import the BaseHTTPServer? can anyone explain me about that? below is the version from Python.org
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
You'll see that there is no import BaseHTTPServer, can anyone explain to me why?
and these code are in Python 2.7 if I want to change it into python 3 Do I still need to import BaseHTTPServer?
Importing it has has meaningful impact, as you have discovered. As for why it is there - who knows? Maybe the author of the tutorial intended to use it later in the tutorial, or maybe it was adapted from a larger sample. The point is if nothing is referencing it, you don't need to import it.
The same applies to python 3.

Categories

Resources