Having trouble getting my http server to recognize and run python scripts - python

I've created a local address http webserver that will hopefully be able to open both HTML webpages and python scripts that create HTML webpages, but I keep getting a 501 error because I can't figure out how to get the webserver to recognize the code correctly. Another note: I'm coding on Windows, I'm not using Cygwin (I don't know anything about Cygwin, so if it's the recommended method here tips on how to get started with it would be appreciated.)
Anyways, here's what I've got.
I have created a folder in C:\ called server_test, and inside this folder is where I have been putting all my relevant HTML and python files. I've been editing my .py files in PyDev in eclipse (C:\workspace) and then copying the files over and putting them in C:\server_test.
To get my server running, I navigate to \server_test in cmd, open python, then create a webserver using HTTPServer, CGIRequestHandler, the current directory, address 127.0.0.1, and a port of my choosing (usually 9090). Once I've done this, I can go to my web browser and type in the address for one of my HTML pages and it runs perfectly fine. However, I currently have an HTML page meant to call a python script (also located in \server_test) that will create another HTML page, but I can't get it to work.
My HTML code looks like this:
<html>
<title>Debug Page</title>
<body
<h1>This is a test file. </h1>
<form method=POST action="my_code_2.py">
<P><input type=submit>
</form>
</body></html>
And then my 'my_code_2.py' looks like this:
#!C:\Python35-32\python.exe
import cgi
import cgitb; cgitb.enable()
print("Content-type: text/html\r\n\r\n")
print('<html>')
print('<h1>')
print('<title>This is a second test.</title>')
print('</h1>')
print('</body')
print('</html>')
From what I've read about shebang lines, it appears Windows native doesn't support them? So how can I make sure that my computer knows it's supposed to run the code as Python? At the moment, when I press the button on my first HTML page, the page http://127.0.0.1:port/my_code_2.py is merely a white page with my python code printed on it.

Try changing the extension to .cgi on your python file and see if that helps. You'll probably want to use something like bottle.py or django tho if you're running python on a webserver. Bottle is easier to learn but with fewer features.
http://bottlepy.org/docs/dev/index.html
https://www.djangoproject.com/

Related

Twisted web problem when serving docx files

I have a question for you!
I'm running a simple webserver with twistd web and it works great must of the time. I have a problem serving .docx files.
Let me explain with an example.
On my webserver I have two files: file.pdf and file.docx (the x is important).
Now, on my browser, if I enter the URL of the pdf file, the browser will start the download (or open it depending on user preferences). This is the expected behavior.
But if I enter a link to a docx, instead of downloading it, the browser will display it as a sequence of strange letters and numbers.
It is not a browser issue, because if a click on a docx file served from another webserver, the browser will download it.
I'm starting the webserver directly from the windows cmd prompt using twistd. The line looks like this:
twistd -no web --path d:\shares\
The question is: how can I tell twistd to force the download of docx file the same way it does for pdf?
Thanks
It might help if you shared some of your code, but I think the basic idea is that you should add the correct MIME type to the header that your server returns, which will help the browser know what to do with it rather than try to render it as text. Based on the docs here it looks like you want something like this:
from twisted.web import static
root = static.File("/files")
root.contentTypes[".docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Using the somewhat long-winded MIME type for docx.

Connecting HTML with Python

I tried to link my HTML file with Python code.
I tried this
import webbrowser
webbrowser.open_new_tab("data.HTML")
It returned my HTML page in Firefox..
But i need to return to my Python program to execute remaining lines
But when I closed this browser, it closes my Python script too.
And I tried to link my Python program by,
go to Python
it returns to text editor not to terminal...
But I need to return to terminal.
I need the solution
As someone described, you need to use one web framework (like flask, django others) to run python code. Or the second solution is using CGI(http://modwsgi.readthedocs.io/en/develop/).
For the second problem(want to keep running python code after browser is closed), I want to advice to use Selenium.
Cheers, John

Import Python codes inside HTML file

As mentioned here, I can import Python codes inside .html files using <% and %> tags. Just to try it, I wrote the below code in notepad and save it as a file named test.html :
<html>
<title>
</title>
<body>
<%print ("Hello")%>
</body>
Once I do a double click on the test.html, Chrome opens with the below line on the top :
<%print ("Heloo")%>
What I must I do to have 'Hello' in output?
Note: "print" is an example, What kind of ways is there to import and run python codes in html files?
That page is related to Karrigell a Python web framework, you can only have Python and HTML files (Web pages) if you use a Python web framework like web.py, Pylons, Django, and others.
Browsers can only execute JavaScript code, other programming languages have to use special components to be executed by browsers.

Python cgi script not opening a html file in local directory

I have a simple python module that generates a web page containing a list of links. This page is automatically opened in a browser through webbrowser.open('file://' + file.name): no problems here.
From this web page, when clicking on on a link (which has a href like http://localhost/cgi-bin/script.py?param1=Something) it lunches a cgi script that performs some operations with the passed value and at the end generates a new web page, stored locally in my machine (e.g. in a path like /home/user/web/out/) in a folder where I correctly set all rwx permissions.
Well, I've been trying to automatically open this new page in the browser for two days now, attempting with all the solutions I found searching through documentations and forums. I tried with webbrowser.open() again, but then I realized that I can't use it because from the web server I can't open a new browser window itself. Then I tried with redirection, printing first a header (print "Content-type: text/html\n\n") and then
print "Status: 302 Moved"
print "Location: file:///home/user/web/out/abc.html\n\n"`
but this just shows a plain blank page. I gave a try to other redirecting solutions, like
print "<meta http-equiv='refresh' content='0' url='file:///home/user/web/out/abc.html'>"
print "<script type="text/javascript">location.href='file:///home/user/web/out/abc.html';</script>"
print "<script type="text/javascript">windows.open('file:///home/user/web/out/abc.html');</script>"
I even tried inserting a Button with a POST method that triggers the opening of the new page, without success: I keep getting a plain blank page.
It is worth to say that, if I manually open this abc.html page in the browser, it is properly shown.
I think this has to do with the fact that the html page I'm opening from the web server is in locally stored, but I don't know how to solve this. Can somebody point me to the right direction?
A CGI-Script can not redirect I remember.
Note that status code 200 is sent prior to execution of a CGI script, so
scripts cannot send other status codes such as 302 (redirect).
This is some code:
self.send_response(200, "Script output follows")
module: http.server (Python 3)
But you can just open the file and use sys.stdout.write or shutil to copy its content to stdout.

retrieve local html form

I have a html page that contains a form and I would like a user to be able to input some data in the form. I would then retrieve this data with a python script.
I don't understand how to make the html and python communicate. How can the python retrieve the form after the user has clicked on post? Is there a basic example I can use to demonstrate this?
What you need is an HTTP server. Python can be used to make a server, or you could get one such as Apache or Lighttpd. I wrote an example application (Rock, Paper, Scissors) based off of this a while ago: https://dl.dropboxusercontent.com/u/95437705/RPS_Web.tgz
C0deH4cker is right that you should have your python program running somewhere in some kind of web server.
A proper way to do this for larger projects is to use a web framework like Django or Web2py. These frameworks have excellent documentation and tutorial pages that are well worth the effort of consuming. A smaller benefit is that both have their own built-in webserver for development an small deployment.
Another way is to write python code that has a web server of its own. You could have a look at Twisted, the networking framework for python. Good info is at http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html.
Finally -- but this is considered a bit outdated, I guess (??) -- there is the CGI option you describe. Most web servers like apache and lighttpd have the option to run CGI scripts. CGI scripts are very simple programs that, in their simplest form, when run, output HTML code on their stdout. The webserver looks at the first ("shebang") line in the script to determine the script interpreter, executes the script, picks up the output and serves it over HTTP.
Specific provisions have been made in CGI for parameter passing. In the Python CGI module, these are obtainable through cgi.FieldStorage()
First for some HTML:
An HTML form has an "action" and a "method" attribute. Action is the URL (absolute, or relative to the current path) where it will send the form data to; Method is the method to use, usually for a form with a submit button this is "POST".
So if you have this HTML code running somewhere:
<html>
<body>
<form name="sample" action="cgi-bin/myscript.cgi" method="post">
Name: <input type="text" name="name"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
When the user presses the submit button, all input values are posted to the URL "myprogram.cgi".
A good text on what CGI code should look like is in http://docs.python.org/library/cgi.html .
Some code that should work is:
import cgi
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<body>\n"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
form = cgi.FieldStorage()
if "name" not in form:
print "<H1>Error</H1>"
print "Please fill in the name fields"
else:
print "<p>name:", form["name"].value
print "</body>"
Now, it is important that you realize that you have to make this code available on the specified URL from a web server. How you should do this depends on your web server.
On apache under linux, you would normally put the script in /var/www/cgi-bin. Possibly you should enable cgi execution in the apache configuration, as it may be switched off for security reasons.

Categories