Untitled
unknown
python
3 years ago
3.3 kB
10
Indexable
import os
import cherrypy # поганий вибор фреймворку, мале ком'юніті, не часто оновлюється, посіда почотнэ останне місце на техэмповер https://www.techempower.com/benchmarks/#section=data-r18&hw=ph&test=fortune&l=zijzen-1
# по PEP8 імпорти стандартних бібліотек відокремлюються від імпортів сторонніх бібліотек пустою строкою https://peps.python.org/pep-0008/#imports
class Root(object): # object не потрібно вказувати в Python 3
pass
# на весь код нема жодної аннотації типів
@cherrypy.expose
class FileService(object): # object не потрібно вказувати в Python 3
def GET(self, filename): # методи классу потрібно вказувати в нижньому регістрі https://peps.python.org/pep-0008/#method-names-and-instance-variables
if not os.path.exists(filename):
cherrypy.response.status = 404
return
cherrypy.response.headers["Content-Type"] = "application" # захардкоджений content-type
# не реалізовано content-desposition https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/Content-Disposition тому із постмана не можна завантажити файл з його назвою
with open(filename, "rb") as f:
return f.read()
def POST(self, file): # методи классу потрібно вказувати в нижньому регістрі https://peps.python.org/pep-0008/#method-names-and-instance-variables
upload_path = os.path.dirname(__file__)
upload_filename = file.filename
upload_file = os.path.normpath(os.path.join(upload_path, upload_filename))
size = 0 # забагато зайвих змінних і коду виглядає як copy-paste
with open(upload_file, "wb") as out:
while True:
data = file.file.read(8192)
if not data:
break
out.write(data)
size += len(data)
def HEAD(self, filename): # методи классу потрібно вказувати в нижньому регістрі https://peps.python.org/pep-0008/#method-names-and-instance-variables
try:
# неправильно реалізовано, HEAD повинен повертати все те ж саме, що і GET, але без тіла https://developer.mozilla.org/ru/docs/Web/HTTP/Methods/HEAD
cherrypy.response.headers["File-Stat"] = str(os.stat(filename))
except FileNotFoundError:
cherrypy.response.status = 404
if __name__ == "__main__":
PATH = os.path.abspath(os.path.dirname(__file__))
conf = {
"/": {
"request.dispatch": cherrypy.dispatch.MethodDispatcher(),
"tools.sessions.on": True,
"tools.response_headers.on": True,
"tools.response_headers.headers": [("Content-Type", "text/plain")],
}
}
cherrypy.quickstart(FileService(), "/files", conf)
Editor is loading...