如何在python中为HTML建立响应头?

时间:2019-12-29 07:13:27

标签: python html browser tcp

我正在使用Internet浏览器作为连接到下面python服务器的客户端。该代码应在浏览器中打开请求的文件,例如/localhost:8888/a/b/ref.html,变量**size_of_file**破坏了我的结果。 而且,如果我将值123硬编码为字符串,则一切正常,但是如果将其用作变量,则浏览器中不会出现任何结果。我不知道这是怎么回事?

while True:
  connection, address = my_socket.accept()
  request = connection.recv(2048).decode('utf-8')

  string_list = request.split(' ')  # Split request from spaces

  method = string_list[0]
  requesting_file = string_list[1]

  myfile = requesting_file.split('?')[0]  # After the "?" symbol not relevent here

  size_of_file = '123'

  myfile = myfile.lstrip('/')
  if (myfile == ''):
    myfile = 'index.html'  # Load index file as default
  try:
    print(myfile)
    # file size

    file = open(myfile, 'rb')  # open file , r => read , b => byte format
    response = file.read()
    file.close()

    header = 'HTTP/1.1 200 OK\n' + 'Connection: keep-alive\n' + "Content-Length:"+size_of_file+'\n'

    print(header)
    if (myfile.endswith(".jpg")):
        mimetype = 'image/jpg'
    elif (myfile.endswith(".css")):
        mimetype = 'text/css'
    else:
        mimetype = 'text/html'

    header += 'Content-Type: ' + str(mimetype) + '\n\n'
    # header += 'Content-Length: ' + str(size_of_file) + '\n\n'

    except Exception as e:
    header = 'HTTP/1.1 404 Not Found\n\n'
    response = '<html><body><center><h3>Error 404: File not found</h3><p>Python HTTP Server</p></center></body></html>'.encode(
        'utf-8')

  final_response = header.encode('utf-8')
  final_response += response
  connection.send(final_response)
  connection.close()

请帮助我解决此问题

0 个答案:

没有答案