即使变量是全局分配的,Python中的UnboundLocalError

时间:2018-07-26 09:17:02

标签: python

为什么在全局分配了Html_code_1和Html_code 2的情况下运行以下代码块会产生未绑定的错误,所以为什么python解释器将其作为局部变量。我正在使用无业游民的机器来运行此代码。

以下是错误消息:

Exception happened during processing of request from ('10.0.2.2', 55545)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 290, in 
_handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 318, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
    self.handle()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
    self.handle_one_request()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 328, in handle_one_request
    method()
  File "true.py", line 31, in do_GET
    Html_code_1 +="<ul>"

代码如下:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


Html_code_1 = """
              <!Doctype html>
              <head><title>Foodpanda.com</title></head>
              <body>
"""    
Html_code_2 = """
              </body>
              </html>
"""

class webServerHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            Html_code_1 +="<ul>"
            Html_code_1 += "</ul>"+Html_code_2
            output = Html_code_1
            self.wfile.write(output.encode())
            return
        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)
def main():
    try:
        port = 8080
        server = HTTPServer(('', port), webServerHandler)
        print "Web Server running on port %s" % port
        server.serve_forever()
    except KeyboardInterrupt:
        print " ^C entered, stopping web server...."
        server.socket.close()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

在调用do_GET函数write时

global Html_code_1

使其在该功能中可用