2

我正在尝试从 Python 中的函数内部提取变量的值,但遇到了一些麻烦。

uri = None
clientHostname = None
clientIP = None
...
# Handles requests
class DataHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(dServe):
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        dServe.end_headers()
    def do_GET(dServe):
        global uri
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        uri = dServe.path
        dServe.end_headers()
        clientHostname = dServe.address_string()
        clientIP = dServe.connection.getsockname()[0]
    print(uri)
    print(clientHostname)
    print(clientIP)

当我尝试执行此操作时,它们仅返回值“无”。任何指针?这是我对 Python(2.7) 的第一次尝试,我仍在攀登它的钟形曲线。

我的完整脚本目前是:

import time
import BaseHTTPServer
import StringIO
import csv
import sqlite3 as sql
import SimpleHTTPServer
import SocketServer
import multiprocessing
import os


# Initial Variables
appsTable = "Apps"
groupsTable = "Groups"
hostName = 'localhost'
dataPort = 277
filePort = 438
dbFile = "Get-App.db"
uri = None
    clientHostname = None
    clientIP = None
if os.name == "nt":
    dbPath = "Dependencies\sqlite3"
else:
    dbPath = "Dependencies/sqlite3"

# Checks for DB and creates if not found
if os.path.exists(dbFile):
    print("Database found!")
else:
    print("Creating New Database...")
    os.system("echo .tables | " + dbPath + " " + dbFile)
    sqlConnect = None
    try:
        sqlConnect = sql.connect(dbFile)
        sqlCursor = sqlConnect.cursor()
        sqlCursor.execute('CREATE TABLE ' + appsTable + '(ID INTEGER PRIMARY KEY ASC, Name TEXT, InstallGroup TEXT, Version TEXT, Arch TEXT, Executable TEXT, Path TEXT, Command TEXT, Latest BOOL, Enabled BOOL)')
        sqlCursor.execute('CREATE TABLE ' + groupsTable + '(ID INTEGER PRIMARY KEY ASC, Name TEXT, AppList TEXT, Version TEXT, Arch TEXT, Latest BOOL, Enabled BOOL)')
    finally:
        if sqlConnect:
            sqlConnect.close

# Serves files
def file_serve():
    if not os.path.exists(dbFile):
        os.makedirs(appsTable)
    os.chdir(appsTable)
    FileHandler = SimpleHTTPServer.SimpleHTTPRequestHandler
    fileServer = SocketServer.TCPServer(("", filePort), FileHandler)
    fileServer.serve_forever()

# Handles requests
class DataHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(dServe):
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        dServe.end_headers()
    def do_GET(dServe):
        global uri
        dServe.send_response(200)
        dServe.send_header("connection-type", "text/html")
        uri = dServe.path
        dServe.end_headers()
        clientHostname = dServe.address_string()
        clientIP = dServe.connection.getsockname()[0]
        dServe.wfile.write(uri)
    print(uri)
    print(clientHostname)
    print(clientIP)


    # This is what's written to the page:
    uriPar = csv.reader(uri, delimiter='?')
    uriEnt = csv.reader(uriPar[0], delimiter='/')
    sqlConnect = sql.connect(dbFile)
    for entity in uriEnt:
        with sqlConnect:    
            sqlCursor = sqlConnect.cursor()
                if entity[1] == "app":
                    if len(entity) == 3:
                        print clientHostname + " made request for app " + entity[2]
                        sqlCursor.execute("SELECT Executable,Path,Command FROM " + appsTable + " WHERE Latest='true' AND Enabled='true' AND Name='" + entity[2] + "'")
                    else:
                        print clientHostname + " made request for app " + entity[2] + ", specifically version " + entity[3]
                        sqlCursor.execute("SELECT Executable,Path,Command FROM " + appsTable + " WHERE Enabled='true' AND Version='" + entity[3] + "' AND Name='" + entity[2] + "'")
                elif entity[1] == "group":
                    if len(entity) == 3:
                        print clientHostname + " made request for group " + entity[2]
                        sqlCursor.execute("SELECT AppList FROM " + groupsTable + " WHERE Latest='true' AND Enabled='true' AND Name='" + entity[2] + "'")
                    else:
                        print clientHostname + " made request for group " + entity[2] + ", specifically version " + entity[3]
                        sqlCursor.execute("SELECT AppList FROM " + groupsTable + " WHERE Enabled='true' AND Version='" + entity[3] + "' AND Name='" + entity[2] + "'")
    rows = sqlCursor.fetchall()
    for place in rows:
        for position in place:
            dServe.wfile.write(position)
            dServe.wfile.write(",")

# Serves http
if __name__ == '__main__':
    dataServer_class = BaseHTTPServer.HTTPServer
    dataServer = dataServer_class((hostName, dataPort), DataHandler)
    print time.asctime(), "Data Service Starts - %s:%s" % (hostName, dataPort)
    print time.asctime(), "File Service Starts - %s:%s" % (hostName, filePort)
    try:
    fileServerThread = multiprocessing.Process(target=file_serve) 
    fileServerThread.start()  # Starts File Server
        dataServer.serve_forever()  # Starts HTTP Server
    except KeyboardInterrupt:
        pass
    dataServer.server_close()
    fileServer.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (hostName, dataPort)
4

2 回答 2

1

首先,代码中的所有print语句都是在加载类定义时执行的,可能不是您真正想要的。

其次,如果这是完整的代码,您永远不会构建和启动您的 HTTP 服务器实例。您需要或多或少这样的代码,它实例化并启动服务器对象:

if __name__ == '__main__':
    httpd = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER), DataHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

此外,以这种方式使用全局变量也不是一个好主意——例如,如果您的服务器同时接受多个连接怎么办?

如果您是 Python 新手,我建议您开始使用现有的工作代码,例如 这个示例

编辑:似乎您的部分代码缩进不正确。看下面的例子:

class Test(object):

    def run(self):
        print 1
    print 2

# By this time, '2' is already printed!
print 3
t = Test()
t.run()

它打印出来:

2
3
1

在您的代码中也是如此 -print语句及其后面的代码缩进 4 个空格,因此它会在解析类时运行(嗯,不完全是,简化一点)。

于 2012-10-26T16:31:06.103 回答
0

你永远不会调用这个do_GET函数,所以uri它仍然是最初设置的。在您调用do_GET某个地方后,您应该会看到uri更新,因为您使用了 global 关键字,但您可能希望在类的定义之外执行此调用和值检查。

于 2012-10-26T16:22:14.497 回答