简体   繁体   中英

Can't include more than one input in webapp2 form

I tried adding an input (text) field to a working example ( https://realpython.com/python-web-applications/ ), and it broke. My Python code is:

import webapp2

def convert_temp(cel_temp):
    if cel_temp == "":
        return ""
    try:
        far_temp = float(cel_temp) * 9 / 5 + 32
        far_temp = round(far_temp, 3)  # round to three decimal places
        return str(far_temp)
    except ValueError:  # user entered non-numeric temperature
        return "invalid input"

class MainPage(webapp2.RequestHandler):
    def get(self):
        cel_temp = self.request.get("cel_temp")
        far_temp = convert_temp(cel_temp)
        self.response.headers["Content-Type"] = "text/html"
        self.response.write("""
        <html>
        <head><title>Temperature Converter</title></head>
        <body>
          <form action="/" method="get">
            <fieldset>
            Celsius temperature: <input type="text" name="cel_temp" value={}><br>
            Dummy: <input type="text" name="dummy" value={}>                        
            <input type="submit" value="Convert"><br>
            Fahrenheit temperature: {}
            </fieldset>
          </form>
        </body>
      </html>""".format(cel_temp, far_temp))

routes = [('/', MainPage)]
my_app = webapp2.WSGIApplication(routes, debug=True)

The new line is the one beginning with "Dummy". The code worked until I put that in, now it throws an internal server error. I'm not getting any clues from looking at HTML doco, so I'm not sure what to try from here.

It's because of the way format works. You need to supply the correct number of arguments at the end, so that you match all the {} with one parameter each. I didn't test it, but this should work, note the empty string as the third argument which should match the third {} :

  self.response.write("""
        <html>
        <head><title>Temperature Converter</title></head>
        <body>
          <form action="/" method="get">
            <fieldset>
            Celsius temperature: <input type="text" name="cel_temp" value={}><br>
            Dummy: <input type="text" name="dummy" value={}>                        
            <input type="submit" value="Convert"><br>
            Fahrenheit temperature: {}
            </fieldset>
          </form>
        </body>
      </html>""".format(cel_temp, far_temp, "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM