【问题标题】:python post and get commandspython post和get命令
【发布时间】:2015-07-23 19:36:25
【问题描述】:

我的发布功能一直有问题。我的应用程序是为人们输入他们的生日而设计的,如果他们输入正确的月、日和年,则发布说“谢谢!那是​​完全有效的一天”,如果不是日期,则发布说“这对我来说似乎无效,朋友”,但它并没有这样做,它只会在我每次推送提交时自行刷新。我的代码在哪里我的 post 函数出错了,还是我的 get 和 post 函数出错了?

import webapp2

form="""  
<form method="post">
    What is your birthday?
    <br>
    <label>Month<input type="type" name="month"></label>
    <label>Day<input type="type" name="day"></label>
    <label>Year<input type="type" name="year"></label>
    <div style="color: red">%(error)s</div>
    <br>
    <br>
    <input type="submit">
</form> 
"""

class MainPage(webapp2.RequestHandler):

    def write_form(self, error=""):
        self.response.out.write(form % {"error": error})

    def get(self):
        self.write_form()

    def valid_year(year):
        if year and year.isdigit():
            year = int(year)
            if year > 1900 and year < 2020:
                return year

    def valid_day(day):
        if day and day.isdigit():
            day = int(day)
            if day > 0 and day <= 31:
                return day

    months = ['Janurary',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']


    month_abbvs = dict((m[:3].lower(),m) for m in months)

    def valid_month(month):
        if month:
            short_month =  month[:3].lower()
            return month_abbvs.get(short_month)




    def post(self):
        user_month = valid_month(self.request.get('month'))
        user_day = valid_day(self.request.get('day'))
        user_year = valid_year(self.request.get('year'))
        if not (user_month and user_day and user_year):
            self.write_form("That doesn't look valid to me, friend.")
        else:
            self.response.out.write("Thanks! That's a totally valid day!")

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

我什至下载了 python IDLE 并使用它而不是 notpad++。 当我推送提交时,我得到了:

 Internal Server Error

The server has either erred or is incapable of performing the requested operation.

Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "C:\Users\ajper_000\Desktop\engineapp\main.py", line 66, in post
    user_month = valid_month(self.request.get('month'))
NameError: global name 'valid_month' is not defined

【问题讨论】:

  • 您的表单如何链接到您的请求处理程序? IE。输入按钮如何知道要发出什么请求?
  • 我认为在解决问题时保留原始代码而不是编辑它可能会更好。否则新读者将难以理解原始问题。您可以改为在问题末尾追加编辑。

标签: python python-2.7 google-app-engine


【解决方案1】:

尝试替换

<form>

<form method="POST">

默认情况下,表单使用 GET 请求,而您的请求处理程序需要 POST 请求。

编辑:看来您有多个问题:

  1. 原来的问题,上面就是答案。
  2. 您的缩进错误,导致 post 方法未定义(或可能在 get 方法中定义)
  3. valid_* 方法未定义 - 您需要定义它们。

【讨论】:

  • 我做了,我得到了 405 Method Not Allowed The method POST is not allowed for this resource.
  • 很奇怪。当缩进错误时,相关问题之一会出现此问题。也许是时候仔细检查拼写和缩进了? stackoverflow.com/questions/10354425/…
  • 嗯,这意味着您确实遇到了缩进问题。现在您遇到了下一个错误,即您没有定义您调用的 valid_... 函数
【解决方案2】:

你应该在valid_month、valid_year和valid_day函数中返回true。就像这段代码

import webapp2

months = ['Janurary',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']


month_abbvs = dict((m[:3].lower(), m) for m in months)


def valid_month(user_month):
    if user_month:
        short_month = user_month[:3].lower()
        return month_abbvs.get(short_month)
    return True


def valid_day(user_day):
    if user_day and user_day.isdigit():
        user_day = int(user_day)
        if user_day > 0 and user_day <= 31:
            return user_day
    return True


def valid_year(user_year):
    if user_year and user_year.isdigit():
        user_year = int(user_year)
        if user_year > 1900 and user_year < 2020:
            return user_year
    return True

form = """
<form method='POST'>
 <h1>What is your birthday?</h1>
 <br>
 <label>Month
 <input type="text" name="month">
 </label>

 <label>day
 <input type="text" name="day">
 </label>

 <label>year
 <input type="text" name="year">
 </label>

 <input type="submit">
</form>
"""


class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write(form)

    def post(self):
        user_month = valid_month(self.request.get('month'))
        user_day = valid_day(self.request.get('day'))
        user_year = valid_year(self.request.get('year'))

        if not (user_year and user_month and user_day):
            self.response.out.write(form)
            self.response.out.write("Please enter valid a function")
        else:
            self.response.out.write('tThanks for that')

app = webapp2.WSGIApplication([('/', MainHandler)], debug=True)

因为调用valid_month函数时,它应该返回True以在浏览器中显示错误消息。

【讨论】:

  • 所以 Raja - 你是说,如果 user_month: 结果为假,我们应该返回 True?您的所有验证都不会返回 false。可怕的建议。对我投反对票。
  • 我们应该返回访问其他中的数据
【解决方案3】:

405 的原因就在堆栈跟踪的底部。

NameError: global name 'valid_month' is not defined

建议您没有名为valid_month 的函数。如果没有,那就写一个。如果你这样做,然后发布它。

【讨论】:

  • 我只是添加了代码,我仍然得到 NameError: global name 'valid_month' is not defined
  • 您添加了valid_dayvalid_year。我没有看到valid_month。添加那个。
  • 我确实添加了 valid_month。它就在所有月份。
【解决方案4】:

Alexander,我在 udacity 上同样的课程,但遇到了同样的问题。但是在进入添加功能以检查用户输入的阶段之前,我只是在老师更改组合框后的代码后立即在浏览器中检查了输出。我遇到了同样的问题,即“405 Method Not Allowed”以及下一行的消息“该资源不允许使用 POST 方法。我扫描了代码并逐行逐字逐字比较使用视频“https://www.udacity.com/course/viewer#!/c-cs253/l-48736183/m-48714317”中的代码,但它没有帮助。

然后我点击了该课程的随附 wiki,并准确复制了我怀疑有问题的 4 行。突然间它奏效了。我使用不同的在线文本比较工具来找出有什么区别,但无法弄清楚问题所在。我在此处复制并粘贴以下两个版本:

版本 1:不工作并给出 405 错误的版本:

def get(self):
    self.response.out.write(form)

def post(self):
    self.response.out.write("Thanks! that's a totally valid day!")

版本 2:适用的版本:

def get(self):
    self.response.out.write(form)

def post(self):
    self.response.out.write("Thanks! That's a totally valid day!")

我看不出这两段代码之间的区别,但即便如此,版本 1 也会出现错误,但版本 2 会给出所需的输出。虽然我已经完全复制并粘贴了 Notepade++ 代码的两个版本(上面给出),但我仍然截取了屏幕截图,以免读者说我可能做了一些缩进问题。以下是两个版本的截图: 版本 1:那不起作用:

第 2 版:可行:

虽然问题目前已解决,但我想知道是什么导致了问题!有哪位python大师能解释一下原因吗?

【讨论】:

    【解决方案5】:

    在类之外和类声明之前和表单结束之后声明方法对我有用。代码是这样的。

    import webapp2
    
    form="""
    
    <form method='POST' >
     What is your birthday
     <br>
     <label>Month
     <input type="text" name="month">
     </label>
    
     <label>day
     <input type="text" name="day">
     </label>
    
     <label>year
     <input type="text" name="year">
     </label>
    
     <input type="submit">
    </form>
    """
    months = ['January',
                     'February',
                     'March',
                     'April',
                     'May',
                     'June',
                     'July',
                     'August',
                     'September',
                     'October',
                     'November',
                     'December']
    
    month_abbvs = dict((m[:3].lower(),m) for m in months)
    
    def valid_month(month):
               if month:
                  shortMonth=month[:3].lower()
                  return month_abbvs.get(shortMonth)
    
    def valid_day(day):
            if day and day.isdigit():
               day=int(day) 
               if day > 0 and day<= 31:
                return day 
    
    def valid_year(year):
             if year and year.isdigit():
                year=int(year)
                if year >=1900 and year <=2020:
                 return year
    class MainHandler(webapp2.RequestHandler):
    
    
        def get(self):
           # self.response.headers['Content-Type']='Text/HTML'
            self.response.write(form)
    
        def post(self):
            user_moth = valid_month(self.request.get('month')) 
            user_day = valid_day(self.request.get('day'))
            user_year = valid_year(self.request.get('year'))  
            #self.response.out.write("Thanks... ")
    
            if not (user_year and user_moth and user_day):
                self.response.out.write(form)
            else:
                self.response.out.write('tThanks for that')
    
    
    
    app = webapp2.WSGIApplication([
        ('/', MainHandler),
    ], debug=True)
    

    希望对您有所帮助。否则您可以将附加参数 self 传递给这些函数定义并使用实例变量调用它

    【讨论】:

    • 你为什么要在课外声明这些?在我看来,他们属于那个阶级。
    • 其实是udacity学习python教程的问题。所以作为一个学习者,我发现它很有效,我可以连接到谷歌应用引擎。就这样。我有可能会出错,但我按照教程进行操作。
    【解决方案6】:

    Python 不会自动将代码范围限定为本地类;你需要告诉它。

    valid_month = self.valid_month(self.request.get('month')) 
    

    您将遇到的下一个错误将是

    TypeError: valid_month() takes exactly 1 argument (2 given)
    

    您需要将“self”声明为“valid_month”方法的第一个参数。

    def valid_month(self, month):
    

    【讨论】:

      猜你喜欢
      • 2011-01-31
      • 2018-12-27
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2021-03-17
      相关资源
      最近更新 更多