0

私はPythonでローカルCGIHttpServerを実行しており、このpythonプログラムを使用してそのサーバーで何かを実行しています:

''' submit data to form using robots '''
import urllib
import pprint


# hacking gullible app
url = "http://localhost:8000/cgi-bin/w5/captcha.example/vote_app/gullible_app.py"

def vote(lecturer):
    params = urllib.urlencode({'lecturer': lecturer,'submit':'submit'})
    f = urllib.urlopen(url, params)
    pprint.pprint(f.fp.readlines())

vote("Ivo")

これは、CGI スクリプトにのみ POST できることを示しています。Python スクリプトが Web ブラウザーでそのアドレスで問題なく開くため、これは非常に奇妙です。だから...それは私のブラウザで正常に実行されていますが、pythonプログラムがそのURLにPOSTしようとしたときではありません。ここで何が起こっているのですか?(これについてインターネット上にはほとんどありません - 私はこの問題を自分で解決するために調査しようとしましたが、この問題について言及している人は3〜4人しかいません)

編集:ごめんなさい!GET と POST がわかりませんでした。これを質問に含めるべきでした-それはpythonプログラム「gullible_app.py」です。ご覧のとおり、フォームは「POST」操作を行います

import cgi
import cgitb; cgitb.enable()

# form generation
# -------------------------------------------------------
def print_form():
    print "Content-Type: text/html\n"
    print '''
<html>
<body>
    <form method="post" action="gullible_app.py">
        <p>Select your favorite lecturer:</p>
        <input type="radio" name="lecturer" value="harald" /> Harald
        <input type="radio" name="lecturer" value="ivo" /> Ivo
        <input type="submit" name="submit" />
    </form>
</body>
</html>
'''

# response generation
# -------------------------------------------------------
def print_response():
    print 'Content-Type: text/html\n'
    print '<html><body>Thank you for your vote!</body></html>'

def main():
    user_data = cgi.FieldStorage()
    if "submit" in user_data: # user press "submit"
        lecturer = user_data.getfirst("lecturer")
        f = open( "cgi-bin\\w5\\captcha.example\\vote_app\\votes.txt", "a" )
        f.write( lecturer+'\n' )
        f.close()
        print_response()
    else: # display the form
        print_form()

main()
4

2 に答える 2

1

サーバー側のプログラム (提供されていないため、確かなことは言えません) は、示されている URL への POST 要求ではなく、GET 要求のみを受け入れます。

urllib は、urlopen を、あなたが行った方法で POST として機能させます。GET であるリクエストを作成する方法の例については、ドキュメントhttp://docs.python.org/2/library/urllib.html#examplesを参照してください。

于 2013-04-17T07:01:20.253 に答える
0

答えはドキュメントにあるようです。

エラー メッセージ:Error 501, “Can only POST to CGI scripts”, is output when trying to POST to a non-CGI url.

大きなヒント:run the CGI script, instead of serving it as a file, if it guesses it to be a CGI script

変更する必要があるもの:cgi_directories

したがって、(Python) CGI スクリプトをデフォルトのサブディレクトリの 1 つに配置するかcgi_directories、URL が CGI スクリプトであると正しく「推測」するように変更します。

于 2013-04-17T06:58:31.623 に答える