Python http.server if语句os.path.isfile()不';行不通
这是我的代码:Python http.server if语句os.path.isfile()不';行不通,python,python-3.x,if-statement,Python,Python 3.x,If Statement,这是我的代码: from http.server import BaseHTTPRequestHandler, HTTPServer import requests, json, os PORT = 1337 class getHandler(BaseHTTPRequestHandler): def handleJSON(self, provider, data): if provider == "provider_1": json_data
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests, json, os
PORT = 1337
class getHandler(BaseHTTPRequestHandler):
def handleJSON(self, provider, data):
if provider == "provider_1":
json_data = json.loads(data)
sl_token = json_data["access_token"]
return sl_token
elif provider == "provider_2":
json_data = json.loads(data)
pb_token = json_data["access_token"]
return pb_token
def do_GET(self):
data = self.requestline
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(b'You may close the tab now')
print("Raw Data: " + data)
if not os.path.isfile("PbToken.txt") and os.path.isfile("SlToken.txt"):
if "GET /?code=" and "&state=" in data: # Provider_1
print("Provider_1 Data:", data)
pb_code = data[data.find("/?code=") + len("/?code="):data.find("&state=")]
with open("PbToken.txt", "w") as file:
file.write(pb_code)
file.close()
elif "GET /?code=" in data: # Provider_2
print("Provider_2 Data:", data)
sl_code = data.strip()
sl_code = sl_code[sl_code.rindex("/?code=") + len("/?code="):sl_code.rindex(" ")]
with open("SlToken.txt", "w") as file:
file.write(sl_code)
file.close()
else:
raise SystemExit
server = HTTPServer(('localhost', PORT), getHandler)
print("Started server on port", PORT)
server.serve_forever()
因此,从函数
do_GET(self)
中的类getHandler
中,如果没有os.path.isfile(“PbToken.txt”)和os.path.isfile(“SlToken.txt”):语句(我当然已经确保文件实际上不在那里),它永远不会通过。我想让它检查这两个文件是否都存在,如果它们没有执行下面写的操作。如果文件存在,它们应该直接转到else
语句,在该语句中使用raisesystemexit
。我做错了什么?应该是或而不是和
因此,只要如果不是os.path.isfile(“PbToken.txt”)或不是os.path.isfile(“SlToken.txt”):
就可以查看其中一个文件是否丢失。您只否定第一个条件(os.path.isfile(“PbToken.txt”)
),而不是第二个条件(os.path.isfile(“SlToken.txt”)
),因此,您正在有效地检查PbToken.txt
是否不存在以及SlToken.txt
是否存在。您是否缺少而不是:和os.path.isfile(“SlToken.txt”):
?Zwer suggetsion是真的。我认为这可能会有所帮助,所以尝试用print(os.path.isfile(“path_file”+I))替换您的条件。您确定您位于正确的文件夹中吗?在该行之前添加print(os.getcwd())
,看看您是否在正确的位置我选中了(os.getcwd
),我确实在正确的文件夹中。对于第一个,我只有而没有
,这是因为真和假
&假和真
都返回假
。所以它会给出同样的结果。