Python: - 将HTML表单输入传递给python代码并执行它

时间:2013-08-23 11:50:15

标签: python html forms cgi

您好我想从html表单获取输入并将其传递给我的python脚本并使其执行然后我想在浏览器中打印我的结果而不使用任何框架。下面是我的python代码:

import re

hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted']

sad=['upset','out','sorry','not in mood','down']

sad_count=0

happy_count=0

str1=raw_input("Enter Message...\n")

happy_count=len(filter(lambda x:x in str1,hap)) 

sad_count=len(filter(lambda x:x in str1,sad))

if(happy_count>sad_count):

        print("Hey buddy...your mood is HAPPY :-)")

elif(sad_count>happy_count):

            print("Ouch! Your Mood is Sad :-(")

elif(happy_count==sad_count):

        if(happy_count>0 and sad_count>0):

            print("oops! You are in CONFUSED mood :o")

        else:
            print("Sorry,No mood found :>")

2 个答案:

答案 0 :(得分:4)

看起来你使用的是python3,但在python 2.7中使用BaseHTTPServer(即python3中的HTTP.server),你可以做一些像这样的事情

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write("""
            <html><head></head>
            <body>
            <form method="POST">
            your mood:
            <textarea name="mood">
            </textarea>
            <input type="submit" name="submit" value="submit">
            </form>
            </body>
            </html>
            """)
        return

    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile, 
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })
        themood = form["mood"]
        hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted']
        sad=['upset','out','sorry','not in mood','down']
        sad_count=0
        happy_count=0
        happy_count=len(filter(lambda x:x in themood.value,hap)) 
        sad_count=len(filter(lambda x:x in themood.value,sad))
        if(happy_count>sad_count):
            self.wfile.write("Hey buddy...your mood is HAPPY :-)")
        elif(sad_count>happy_count):
            self.wfile.write("Ouch! Your Mood is Sad :-(")
        elif(happy_count==sad_count):
            if(happy_count>0 and sad_count>0):
                self.wfile.write("oops! You are in CONFUSED mood :o")
            else:
                self.wfile.write("Sorry,No mood found :>")
        return
server = HTTPServer(('', 8181), Handler)
server.serve_forever()

我希望能帮到你

答案 1 :(得分:0)

如果要在本地计算机上测试它,可以使用python创建一个简单的Web服务器。你可以找到一个好的教程here。您可以编写python脚本来处理数据。 或者另一种方法是安装像Apache或NGinx这样的真实网络服务器并使用cgi或wsgi扩展。第二种方法的优点是,在这种情况下,服务器可以处理html,css,image等文件,因此您可以专注于您的python代码,而不需要编写整个现有的应用程序。