kfahn commited on
Commit
ce34702
1 Parent(s): d34c232

Update fileservice.py

Browse files

adding fileservice.py
refer to https://huggingface.co/spaces/jonigata/PoseMaker2/blob/main/fileservice.py

Files changed (1) hide show
  1. fileservice.py +37 -0
fileservice.py CHANGED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, Response
2
+
3
+ filenames = ["js/sketch.js"]
4
+ contents = '\n'.join([f"<script type='text/javascript' src='{x}'></script>" for x in filenames])
5
+
6
+ app = FastAPI()
7
+
8
+ @app.middleware("http")
9
+ async def insert_js(request: Request, call_next):
10
+ path = request.scope['path'] # get the request route
11
+ response = await call_next(request)
12
+
13
+ if path == "/":
14
+ response_body = ""
15
+ async for chunk in response.body_iterator:
16
+ response_body += chunk.decode()
17
+
18
+ some_javascript = """
19
+ <script type="text/javascript">
20
+ src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js">
21
+ </script>
22
+ <script src="sketch.js"></script>
23
+ """
24
+
25
+ response_body = response_body.replace("</headers>", some_javascript + "</headers>")
26
+ response_body = response_body.replace("</body>", contents + "</body>")
27
+
28
+ del response.headers["content-length"]
29
+
30
+ return Response(
31
+ content=response_body,
32
+ status_code=response.status_code,
33
+ headers=dict(response.headers),
34
+ media_type=response.media_type
35
+ )
36
+
37
+ return response