How do I display a website with html-forms locally using python and collect the user input?

后端 未结 5 1575
猫巷女王i
猫巷女王i 2021-01-06 19:17

I am a behavorial scientist and usually collect data by letting participants do some tasks on a computer and record their responses (I write the programs using the pyglet wr

5条回答
  •  耶瑟儿~
    2021-01-06 19:45

    your want a simple solution, so just write a http server and run your simple page.

    using python.BaseHTTPServer, coding a 15 line web server:

    import BaseHTTPServer
    
    class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == '/foo':
                self.send_response(200)
                self.do_something()
            else: 
                self.send_error(404)
    
        def do_something(self):
            print 'hello world'
    
    server = BaseHTTPServer.HTTPServer(('',80), WebRequestHandler)
    server.serve_forever()
    

    easy enough,but i suggest using some web frameworks. They are easy too.

    for example, web.py. here is what u want in 50 line codes:

    1. install web.py
    2. make a dir with 2 files:

      ./
      |-- app.py
      `-- templates
          `-- index.html
      
    3. index.html

      $def with (form, ret)

      
      
                       another site 
      
      
              

      hello, this is a web.py page

      $:form.render()

      $:ret

    4. app.py logic file:

      import web
      
      ### Url mappings
      
      urls = (
           '/', 'Index', )
      
      ### Templates 
      render = web.template.render('templates')
      
      class Index:
          form = web.form.Form(
              web.form.Textbox('fav_name', web.form.notnull, description="Favorite Name:"),
              web.form.Textbox('cur_name', web.form.notnull, description="Current Name:"),
              web.form.Button('Send Away'),
          )
      
          def GET(self):
              """ Show page """
              form = self.form()
              return render.index(form, "")
      
          def POST(self):
              """ handle button clicked """
              form = self.form()
              if not form.validates():
                  return render.index(form, "INPUT ERROR")
      
              # save data by ur method, or do some task
              #pyglet.save_data(form.d.fav_name, form.d.cur_name)
              #pyglet.draw(some_pic)
              #os.system(some_cmd)
      
              form = self.form()
              return render.index(form, "YOUR DATA SAVED")
      
      app = web.application(urls, globals())
      
      if __name__ == '__main__':
          app.run()
      
    5. run this server in your windows:

      python app.py 9999

    6. open browser: http://127.0.0.1:9999/

    by the way, if ur data is only strings, u can save them in web.by by sqlite.

提交回复
热议问题