I'm trying to write a python script that can be run from a browser and displays a very basic html page.
When I use a multiline code block for the html code the web page displays fine.
When i run the script below in a browser from the cgi-bin folder it displays a blank page. Is there a way to do it in a single line?
#!/usr/bin/env python3
str="test"
print("<html><head></head><body><h1>Sample string:", str, "</h1></body></html>")
The code below is to start the python server that serves the script:
#!/usr/bin/env python3
import http.server
import socketserver
import cgitb
# debugging via de web browser
cgitb.enable(format="text")
Handler = http.server.CGIHTTPRequestHandler
PORT = 8000
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.server_name = ""
httpd.server_port = PORT
print("serving at port", PORT)
httpd.serve_forever()
Related
I'm trying to create mockup telnet server (for some functional testing of existing code). Right now I only modified server welcome message and I was trying to read this message using client code, but it read method fails on timeout with no additional info. But with pudb debugger enabled it works most of the time...
I'm using virtualenv, with pudb and telnetsrv installed using pip. Python 2.7.12, ubuntu 16.04.
Server code:
import SocketServer
from telnetsrv.threaded import TelnetHandler
class MyHandler(TelnetHandler):
WELCOME = "HI from custom server"
class TelnetServer(SocketServer.TCPServer):
allow_reuse_address = True
server = TelnetServer(("0.0.0.0", 8023), MyHandler)
server.serve_forever()
Client code:
import telnetlib
HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data
tn.close()
Client output:
$ python client.py
Data:
Client output with pudb enabled (with step-by-step execution)
$ python client.py
Data: HI from custom server
Of course when I execute shell telnet command, it all works fine:
$ telnet 127.0.0.1 8023
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
HI from custom server
Telnet Server>
I'd really appreciate any hints on how to debug this problem. Thanks!
Be sure there is actually connecting going on. To do that put edit your code to add tn.set_debuglevel(100) into your script to look like this:
import telnetlib
HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
tn.set_debuglevel(100)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data
tn.close()
This will ensure all the data is printed out so you can see what's going on.
My theory is, that you're not connecting, or that your data isn't actually outputting "custom server" and therefor it won't catch it, or your timeout is too low.
I'm creating a simple server to serve a form via Python. The user will post their name and a message through an HTML form, on the server-side python will retrieve these values and append them to a file. I've tested each part on their own, other then the cgi.fieldstorage. When running the code, it returns no errors but will not display my HTML page. Any suggestions?
The Python file is below
#!/usr/bin/python
import sys
import os
import SimpleHTTPServer
import cgi
import SocketServer
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
form = cgi.FieldStorage()
user = form.getvalue("name")
message = form.getvalue("line")
#Append to data.txt
data = open('data.txt', 'a') #open this txt file to then append to it
data.write('%s: %s\n'% (user, message)) #Append this line to the file
data.close()
if __name__=="__main__":
PORT = 9020 #declare which port to serve on.
server = SocketServer.TCPServer(('',PORT),MyHandler) #call the class to generate the server
print "Serving on port: ", PORT #Print what port the Server is serving on
server.serve_forever() #Loop serving requests
I'm a total newbie when it comes to servers, so this question my sound silly to you, but I stucked and I need you help once more.
I have written a simple server in python, which looks like this:
#!/usr/bin/env python
from socket import *
import time
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', 8888))
s.listen(5)
while 1:
client,addr = s.accept()
print 'Connected to ', addr
client.send(time.ctime(time.time()))
client.close()
So when i write localhost:8888 in my browser, i get the message with the current server time.
The next thing i want to do, is to configure my server to allow opening various files from my computer i.e. html or text ones. So when I write in my browser localhost:8888/text.html, this file opens. Where do i start with that?
I should mention I'm using linux mint and don't want to use any existing framework. I want to fully understand how the servers are working and responding.
Try this:
Create a script named webserver.py
import SimpleHTTPServer
import SocketServer
PORT = 8888
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Create a file named text.html and place it on the same dir where your webserver.py script is.
Run python webserver.py
Navigate to http://localhost:8888/text.html
Using a very simple BaseHttpServer (code below) I am experiencing the following problem:
Starting the server in background using ./testserver.py & works fine and the server responses on port 12121 . When I type in disown the server still responses. After closing the terminal the server stops after the next request with Input/output error in test.log
Steps to reconstruct:
$ ./testserver &
$ bg
$ disown
close terminal, send a request to server -> server does not respond.
The only solution I found was to redirect the stdout and stderr:
$ ./testserver > /dev/null 2>&1
or as #Daniel Stated to call it the usual way with nohup
Has anyone experienced this bug before or why is this a desired behaviour for a HttpServer to crash if there is no output possible?
testserver.py
#! /usr/bin/env python
import time
import BaseHTTPServer
HOST_NAME = '0.0.0.0'
PORT_NUMBER = 12121
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
def do_GET(s):
"""Respond to a GET request."""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("MANUAL SERVER SUCCESS")
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
try:
httpd.serve_forever()
except Exception as e:
with open('test.log', 'w') as f:
f.write(str(e))
You only can write strings to files not exceptions. And you have to redirect stdout and stderr somewhere, otherwise any output will hang your program. Why don't you use nohup? That's the normal way, to start programs without terminal.
To make this clear: There is no special behavior in HttpServer. HttpServer is writing log-information to the terminal, so you need a terminal or a redirection to a file.
I'm wanting to run a very simply python based server in a windows environment, to test CGI scripts. I want to do this in windows, but run ultimately in a unix environment. So far, I have a simple server, and a simple program. When I go to the site, I am seeing a blank page, with nothing in the source, and I can't figure out what's going on.
Server
from http.server import HTTPServer, CGIHTTPRequestHandler
class Handler(CGIHTTPRequestHandler):
cgi_directories = ["/cgi-bin"]
PORT = 8080
httpd = HTTPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
httpd.serve_forever()
App:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgi, cgitb
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2>Hello %s %s</h2>" % (first_name, last_name))
print ("</body>")
print ("</html>")
I go to the program in my web browser, and I'm getting a downloadable output, with it being the name of the file. It appears the file has executed, but I'm not getting a valid web site. What am I doing wrong?
Of course I figured out the answer just as I posted it... I should just use a \n\n, not \r\n\r\n.
print ("Content-Type: text/html\n\n")