3

I'm relatively new to Python. I am trying to run a simple server using python. I successfully did this, but I want to have a message such as "Hello World" when I run the server from my browser. It posts my directory when I run the program and says "Directory listing for/" at the top. Is there a way to add more text on this page? How would I do this?

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler


HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

2 Answers 2

2

When you implement such a httpserver and browse it, the do_GET method of the SimpleHTTPRequestHandler is called. And by default it will searches the directory your script is in for index.html or index.htm. If there is no such file, the directory will be displayed.

So if you want to display contents rather than the directory. You should add a file index.html or index.htm in your directory. And writes the contents you want to display in the file.

For more please refer the doc.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with using index.html is that it sends a text/html mime type. If you truly want to send text, you need to use text/plain.
0

You are using SimpleHTTPServer, and while its great, you would have to use CGI for interaction. This answer does not answer your exact question, but I believe it will allow you to do the same with, with ease.

In Python, we use WSGI servers to interact with websites. The reason we do this, is because WSGI scales and can handle a lot more than CGI or Common Gateway Interface. You can take a look @ WSGI, here.

Armin Ronacher wrote this, and he is the author of two popular Python frameworks, Flask and Werkzueg. If you intend to continue learning Python web development, you will meet these frameworks soon.

I realize that this does not answer your question per-se. But, it will allow you to get the same thing, and will give you a foundation that can help you with popular frameworks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.