JPG и JS не работает на сервере, который я пытаюсь сделать - PullRequest
0 голосов
/ 28 января 2020

У меня есть задание о серверах.

Нам пришлось написать сервер на python, который работает с протоколом HTTP.

Это код:

    import socket
    import os
    IP = '0.0.0.0'
    PORT = 80
    SOCKET_TIMEOUT = 60
    DEFAULT_URL = "\index.html"
    REDIRECTION_DICTIONARY = "\page2.html"
    # HTTP Server Shell
    # Author: Barak Gonen
    # Purpose: Provide a basis for Ex. 4.4
    # Note: The code is written in a simple way, without classes, log files or other utilities, for educational purpose
    # Usage: Fill the missing functions and constants

    # TO DO: import modules

    # TO DO: set constants


    def get_file_data(filename):
        """ Get data from file """
        if os.path.exists(filename):
            filetype=filename.rsplit('.',1)[1]
            print("file = "+ filename)
            print(filetype)
            with open(filename, 'rb') as file_obj:
                    file_data = file_obj.read()
            return True,file_data
        else:
            return False,None






    def handle_client_request(resource, client_socket):
        """ Check the required resource, generate proper HTTP response and send to client"""
        # TO DO : add code that given a resource (URL and parameters) generates the proper response

        if resource == '/' or resource == "/index.html":
            url = DEFAULT_URL
        else:
            url = resource
        filetype = url.rsplit(".", 1)[1]
        print("filetype = " + filetype)
        if url in REDIRECTION_DICTIONARY:
            # TO DO: send 302 redirection response
            http_header = "HTTP/1.1\r\n" + "302 Redirected\r\n"
            response = http_header+"Location- p2.html"
            print(b"respoese = " + response)
            client_socket.send(response.encode())

        else:   # TO DO: extract requested file type from URL (html, jpg etc)
            start_header="Content-Type:"
            if filetype == 'html' or filetype == "txt":
                http_header = start_header+" text/html; charset=utf-8"# TO DO: generate proper HTTP header
            elif filetype == 'jpg' or filetype == "png" or filetype == "ico" or filetype == "gif":
                http_header = start_header+" image/jpg"# TO DO: generate proper jpg header
            elif filetype == "js":
                http_header = start_header+" javascript; charset=utf-8"
            else:
                http_header=start_header+" text/css"
            # TO DO: handle all other headers

            # TO DO: read the data from the file
            prefix_dir = r"C:PycharmProjects\4.4 work\webroot"
            url = prefix_dir+url
            check, data = get_file_data(url)
            print('what = '+url)
            if check:

                http_header = http_header.encode()
                data_len = str(len(data)).encode()
                http_response = b"http/1.1\r\n"+b"200 OK\r\n"+b"Content-Length: "+data_len+b"\r\n"+http_header+b"\r\n"+data
                print(b"http_respone =" + http_response)
                client_socket.send(http_response)
            else:
                http_response = "404 Not Found"
                print("http_respone =" + http_response)
                client_socket.send(http_response.encode())


    def validate_http_request(request):
        """ Check if request is a valid HTTP request and returns TRUE / FALSE and the requested URL """
        request = request.decode()
        split_request = request.split(" ")
        print(split_request[2])
        if split_request[0] == 'GET' and split_request[2].startswith("HTTP/1.1"):
            return True, split_request[1]
        return False, split_request[1]

        # TO DO: write function


    def handle_client(client_socket):
        """ Handles client requests: verifies client's requests are legal HTTP, calls function to handle the requests """
        print('Client connected')
        while True:
            client_request = client_socket.recv(1024)
            print(b"req =  "+ client_request)
            valid_http, resource = validate_http_request(client_request)
            if valid_http:
                print('Got a valid HTTP request')
                handle_client_request(resource, client_socket)
                break
            else:
                print('Error: Not a valid HTTP request')
                break
        print('Closing connection')
        client_socket.close()


    def main():
        # Open a socket and loop forever while waiting for clients
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind((IP, PORT))
        server_socket.listen(10)
        print("Listening for connections on port %d" % PORT)

        while True:
            client_socket, client_address = server_socket.accept()
            print ('New connection received')
            try:
                client_socket.settimeout(SOCKET_TIMEOUT)
                handle_client(client_socket)
            except socket.timeout:
                print("error")
                client_socket.close()

    if __name__ == "__main__":
        main()

Кроме того, у меня есть папка со всем, что мне нужно для этой страницы. (Я не уверен, как загрузить файлы / папки здесь, так что, если кто-нибудь знает, скажите мне, и я буду загружать их)

На странице есть три изображения:

  1. поддерживает CSS
  2. поддерживает JPG
  3. поддерживает JS

Но работает только фотография CSS, две другие - нет.

Если кто-нибудь знает, почему, пожалуйста, ответьте.

Спасибо.

...