【问题标题】:'Indentation Error - expected an indented block' when dealing with header'缩进错误 - 处理标题时需要一个缩进块'
【发布时间】:2017-08-23 12:03:52
【问题描述】:

由于我是编程新手,代码中可能还有其他我没有检测到的错误,所以如果您发现任何新手错误或不良风格,请指出。我正在尝试实现一个简单的 Web 服务器,但在服务器创建 HTTP 响应消息的部分不断收到缩进错误,该消息由请求的文件和标题行组成。

from socket import *
import sys

host = 'localhost'
serverPort = int(sys.argv[1])
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((host,serverPort))
serverSocket.listen(1)

while True:
    connectionSocket, addr = serverSocket.accept()

    try:
        #if received correct stuff
        File_Wanted = connectionSocket.recv(1024)
        File_Name = File_Wanted.split()[1]
        #open and read line in index.htm
        File = open('index.htm','r')
        output = File.read()
        #should I close it here or somewhere else?
        File.close()

        #take care of header first 
        connectionSocket.send('HTTP/1.0 200 OK\r\n')

        #looks good, then send to client(browser)
        for i in range(0, len(output)):
        connectionSocket.send(output[i]) 
        connectionSocket.close()


    IOError:
    #Send response message for file not found
        connectionSocket.send('404 Not Found')                       
    #Close client socket       
        connectionSocket.close()                            


serverSocket.close()

当我建立在崇高之上时,我得到了。

connectionSocket.send(output[i]) 
^

IndentationError: 期望一个识别块

【问题讨论】:

  • Python使用空格定义块,for语句后面的行需要缩进
  • 在 serverSocket.close() 之后尝试缩进
  • for 循环后缩进行以获取应该在 for 中的代码
  • 你显然错过了 try-except 块中的 except 关键字(IOError 行)。应该是except IOError:

标签: python sockets http-headers


【解决方案1】:

Python使用空格来定义块,你需要在for语句后缩进:

for i in range(0, len(output)):
    connectionSocket.send(output[i]) 
    connectionSocket.close()

在检查错误之前你需要一个except 声明:

except IOError:

【讨论】:

    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多