python - http.server在windows上工作,但在debian上不起作用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python - http.server在windows上工作,但在debian上不起作用相关的知识,希望对你有一定的参考价值。

所以我对python相对较新,但我认为我是一个快速学习者。为了与我的某个程序进行通信,我制作了这个简单的网络服务器:

from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
import time

class S(BaseHTTPRequestHandler):
    class user():
        def __init__(self, name, hash):
            self.name = name;
            self.hash = hash;
        def terminate(self):
            pass;
    def _set_headers(self, res=200, type="text/html", loc=False):
        self.send_response(res)
        if loc:
            self.send_header('Location', loc)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers(200)
        self.wfile.write(b"<tt><h1>UGame-Server.</h1></tt><hr>Incorrect Method.")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        if self.headers.get('Content-Length'):
            data = json.loads(self.rfile.read(int(self.headers.get('Content-Length'))));
        else:
            data = {};
        datas = json.dumps(data);
        if self.path == "/":
            self._set_headers(200, "text/html", "index");
            self.path = "/index";
        else:
            self._set_headers(200, "text/html");
        path = self.path[1:];
        print(path);
        import index as serverfile;
        auth=True;
        if path[:6]=="secure":
            auth=False;
            os.chdir("axs");
            if "hash" in data:
                if os.path.exists(data["hash"]+".txt") and time.time()-os.path.getmtime(data["hash"]+".txt")<43200:
                    auth=True;
                    print("Secure access from account "+data["name"]+" verified.");
                    data["user"]=self.user(data["name"],data["hash"]);
                #   del data["name"];
            else:
                if self.client_address[0]=="127.0.0.1":
                    auth=True;
                    data["user"]=self.user("admin","fake");
                    data["name"]="admin";
            os.chdir("..");
            if auth:
                psfr = open("serverdata.posdata.json", "r" );
                posdata = json.loads(psfr.read());
                psfr.close();
                if data["name"] in posdata:
                    data["user"].x = posdata[data["name"]]["x"];
                    data["user"].y = posdata[data["name"]]["y"];
                    data["user"].z = posdata[data["name"]]["z"];
                    data["user"].world = posdata[data["name"]]["world"];
        if auth:
        #   try:
            exec("global response; response = serverfile."+path+"(data);");
        #   except AttributeError:  
        #       exec('global response; response = "Method not found.";');
        else:
            exec('global response; response = "Authentification Failed.";');
        print("Sending response: "+response);
        self.wfile.write(bytes(response, 'utf8'));


def run(server_class=HTTPServer, handler_class=S, port=1103):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd...');
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

现在的问题是,这个东西在Windows上运行得非常好,并且确实应该完全正确。但是一旦谈到Debian,我的VPS运行的操作系统,它首先意味着它,它立即在第一行崩溃。它似乎无法导入http.server,因为数百个语法错误来自http.client的内部代码。

例如,第一个错误如下:

Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/var/www/html/ugame-server/server.py", line 1, in <module>
    from http.server import BaseHTTPRequestHandler, HTTPServer
  File "http/server.py", line 92, in <module>
    import http.client
  File "http/client.py", line 144
    _is_legal_header_name = re.compile(rb'[^:s][^:
]*').fullmatch
                                                         ^
SyntaxError: invalid syntax

我检查了所有可用的更新,我的系统,python和所有模块都是最新的。

  • 显然我错了。

Windows中出现的错误中没有一个出现。我不明白。感谢帮助。

编辑:更新Debian修复了一些错误,但出现了新错误:

Traceback (most recent call last):
  File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/var/www/html/ugame-server/server.py", line 1, in <module>
    from http.server import BaseHTTPRequestHandler, HTTPServer
  File "/var/www/html/ugame-server/http/server.py", line 92, in <module>
    import http.client
  File "/var/www/html/ugame-server/http/client.py", line 1063
    chunk = f'{len(chunk):X}
'.encode('ascii') + chunk 
                                ^
SyntaxError: invalid syntax
答案

re.compile(rb'[^:s][^: ]*'是Python 2中的无效语法,因此请查看启动服务器时实际使用的版本

根据第二个错误,f-strings是Python 3.6的可访问起点:https://realpython.com/python-f-strings/

以上是关于python - http.server在windows上工作,但在debian上不起作用的主要内容,如果未能解决你的问题,请参考以下文章

python金融分析小知识(27)——如何通过python连接Wind(万得)数据库

python气象绘图windrose

python [wind.selected.FTCA]

python [tp。收益曲线]获得突破个股的今年以来的收益比较图#wind

python [寻找一组股票的历史最低价并和现价比较] #tags:wind,IO

Python快速创建一个简易 HTTP 服务器(http.server)