3

私は単にPythonサーバーを作成しました:

python -m SimpleHTTPServer

私は.htaccessを持っていました(Pythonサーバーで役立つかどうかはわかりません):

AddHandler cgi-script .py
Options +ExecCGI

今、私は簡単な python スクリプトを書いています:

#!/usr/bin/python
import cgitb
cgitb.enable()
print 'Content-type: text/html'
print '''
<html>
     <head>
          <title>My website</title>
     </head>
     <body>
          <p>Here I am</p>
     </body>
</html>
'''

test.py (スクリプトの名前) を実行ファイルにします。

chmod +x test.py

私は次のアドレスで Firefox を起動しています: (http : //) 0.0.0.0:8000/test.py

問題、スクリプトが実行されません... Web ページにコードが表示されます... サーバー エラーは次のとおりです。

localhost - - [25/Oct/2012 10:47:12] "GET / HTTP/1.1" 200 -
localhost - - [25/Oct/2012 10:47:13] code 404, message File not found
localhost - - [25/Oct/2012 10:47:13] "GET /favicon.ico HTTP/1.1" 404 -

Pythonコードの実行を簡単に管理するにはどうすればよいですか? 次のようなPythonスクリプトを実行するためにPythonサーバーに書き込むことは可能ですか?

import BaseHTTPServer
import CGIHTTPServer
httpd = BaseHTTPServer.HTTPServer(\
    ('localhost', 8123), \
CGIHTTPServer.CGIHTTPRequestHandler)
###  here some code to say, hey please execute python script on the webserver... ;-)
httpd.serve_forever()

または、他の何か...

4

3 に答える 3

8

組み込みの http サーバーにとってファイルは何の意味もないためCGIHTTPRequestHandler、正しい軌道に乗っています。実行可能ファイルが cgi スクリプトと見なされるディレクトリを指定.htaccessする変数があります (ここにチェック自体があります)。またはディレクトリに移動することを検討し、次のスクリプトを使用する必要があります。CGIHTTPRequestHandler.cgi_directoriestest.pycgi-binhtbin

cgiserver.py:

#!/usr/bin/env python3

from http.server import CGIHTTPRequestHandler, HTTPServer

handler = CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi-bin', '/htbin']  # this is the default
server = HTTPServer(('localhost', 8123), handler)
server.serve_forever()

cgi-bin/test.py:

#!/usr/bin/env python3
print('Content-type: text/html\n')
print('<title>Hello World</title>')

最終的には次のようになります。

|- cgiserver.py
|- cgi-bin/
   ` test.py

で実行しpython3 cgiserver.py、リクエストを に送信しますlocalhost:8123/cgi-bin/test.py。乾杯。

于 2012-10-25T10:57:28.890 に答える
3

Flaskを使ってみましたか? これは、これを非常に簡単にする軽量のサーバー ライブラリです。

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return '<title>Hello World</title>'


if __name__ == '__main__':
    app.run(debug=True)

この場合の戻り値<title>Hello World</title>は HTML でレンダリングされます。より複雑なページには、HTML テンプレート ファイルを使用することもできます。

これは、それをよりよく説明する優れた短いYouTubeチュートリアルです。

于 2016-09-21T14:27:56.390 に答える