wygeneruj mi w pythonie server, ktory po uruchomieniu bedzie wczytywal dane z plik…
- User
wygeneruj mi w pythonie server, ktory po uruchomieniu bedzie wczytywal dane z plik (C:/plik.txt). Nastepnie powinien posiadac funkje(Metoda() ). Uzytkownik powinien moc wywowac te metode poprzez przegladarke (cos w stylu; http://mojserver/Metoda), kiedy ta metoda zostanie wywolana, tresc pliku powinien zostac wypisany na ekranie
Assistant
Oto prosty serwer HTTP w Pythonie, który spełnia Twoje wymagania:
from http.server import HTTPServer, BaseHTTPRequestHandler import os class MyHandler(BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): # Wczytaj dane z pliku przy inicjalizacji self.file_path = "C:/plik.txt" self.file_content = self.load_file_content() super().__init__(*args, **kwargs) def load_file_content(self): """Wczytuje zawartość pliku""" try: if os.path.exists(self.file_path): with open(self.file_path, 'r', encoding='utf-8') as file: return file.read() else: return f"Plik {self.file_path} nie istnieje" except Exception as e: return f"Błąd podczas wczytywania pliku: {str(e)}" def do_GET(self): """Obsługuje żądania GET""" if self.path == '/Metoda': self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() # Wyślij zawartość pliku jako odpowiedź HTML html_response = f""" <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Zawartość pliku</title> </head> <body> <h1>Zawartość pliku C:/plik.txt:</h1> <pre>{self.file_content}</pre> </body> </html> """ self.wfile.write(html_response.encode('utf-8')) else: # Dla innych ścieżek wyświetl instrukcję self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() html_response = """ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Mój Serwer</title> </head> <body> <h1>Witaj na moim serwerze!</h1> <p>Aby wywołać metodę i wyświetlić zawartość pliku, przejdź do:</p> <a href="/Metoda">http://localhost:8000/Metoda</a> </body> </html> """ self.wfile.write(html_response.encode('utf-8')) def run_server(): """Uruchamia serwer""" server_address = ('localhost', 8000) httpd = HTTPServer(server_address, MyHandler) print("Serwer uruchomiony na http://localhost:8000") print("Aby wywołać metodę, przejdź do: http://localhost:8000/Metoda") print("Naciśnij Ctrl+C aby zatrzymać serwer") try: httpd.serve_forever() except KeyboardInterrupt: print("\nSerwer zatrzymany") httpd.server_close() if __name__ == "__main__": run_server()Jak używać:
- Zapisz kod w pliku (np.
server.py) - Upewnij się, że masz plik
C:/plik.txtz jakąś zawartością - Uruchom serwer:
python server.py - Otwórz przeglądarkę i przejdź do
http://localhost:8000/Metoda
Funkcjonalność:
- Serwer wczytuje dane z
C:/plik.txtprzy starcie - Dostępny jest pod adresem
http://localhost:8000 - Metoda dostępna pod
/Metodawyświetla zawartość pliku - Obsługuje błędy (brak pliku, problemy z kodowaniem)
- Wyświetla instrukcje na stronie głównej
Jeśli chcesz zmienić port lub ścieżkę do pliku, możesz zmodyfikować odpowiednie zmienne w kodzie.
- Zapisz kod w pliku (np.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.