Python - http.server работает на Windows, но не на Debian - PullRequest
0 голосов
/ 10 сентября 2018

Так что я относительно новичок в 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][^:\r\n]*').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}\r\n'.encode('ascii') + chunk \
                                ^
SyntaxError: invalid syntax

1 Ответ

0 голосов
/ 10 сентября 2018

re.compile(rb'[^:\s][^:\r\n]*' является недопустимым синтаксисом в Python 2, поэтому посмотрите, какую версию вы на самом деле используете при запуске сервера

В соответствии с ошибкой в ​​секунду, f-строки являются доступными, начиная с Python 3.6: https://realpython.com/python-f-strings/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...