开发者

how to run .py file in browser using python webserver

开发者 https://www.devze.com 2023-04-10 15:51 出处:网络
i have running a python webserver by using this simple script - from http.server import SimpleHTTPRequestHandler as RH

i have running a python webserver by using this simple script -

    from http.server import SimpleHTTPRequestHandler as RH
    from socketserver import TCPServer

    ServerName='localhost'
    开发者_Python百科OnPort=8000
    print ("Server is running at Port 8000")
    TCPServer((ServerName, OnPort), RH).serve_forever()

it is running good and run my index.html file but it is not run .py file in browser when i type -- http://localhost:8000/myfile.py

it just show my python codes as it is i write in file ,it is not execute the code please help me to run my python file (.py) in browser by using this webserver only ,i don't want to use any framework or another webserver.

Is there any way to make a virtual host in this python server like apache. if possible please suggest me that how to do this and any configuration file need to be configured or not.

thanx...


The problem is that SimpleHTTPRequestHandler only serves files out of a directory, it does not execute them. You must override the do_GET method if you want it to execute code.


You might want to check out CGIHTTPRequestHandler instead. I very briefly played with it on a linux based system and the CGI criteria was for a file to be executable and have the correct shabang. I'm not sure if this would work on Windows though ( if that is even a relevant concern )

With your example code you would only need to change RH to

import CGIHTTPServer.CGIHTTPRequestHandler as RH

Alternatively the 3rd party library Twisted has a concept of .rpy files that are mostly plain Python logic. http://twistedmatrix.com/trac/wiki/TwistedWeb

Note: Just verified that the CGIHTTPRequestHandler works. Caveats is that all python files must be in a cgi-bin subdir, they must have a valid shabang, must be executable, and must provide valid CGI output.

Personally having written C++ CGI scripts in the 90's, the CGI route seems like the path to maddness... so check out Twisted, CherryPy, or Django ( those three mostly cover the Python web spectrum of possibilities )

0

精彩评论

暂无评论...
验证码 换一张
取 消