#Docker Flask application
623 messages · Page 1 of 1 (latest)
My backend is weirdly done, every other guide on the internet always either has only one flask file called app.py or has some kind of running done in that flask python file.
My dockerfile so far:
# syntax=docker/dockerfile:1
FROM python:3.10
WORKDIR /app
ADD backend/requirements.txt /app/
ADD backend/* /app/
ADD frontend/* /app/
RUN pip3 install -r requirements.txt
CMD ["gunicorn", "-b", "0.0.0.0:8000", "backend:app"]
I'm pulling both my backend and frontend folder with it's contents to my working directory /app and I'm kind of hoping it to start working. I did some research on it, but most of the guides have really simple flask apps in them, so that complicates it.
u need to specify context in the docker build command
You should add a docker ignore file to ignore __pycache__, .pytest_cache, and venv
Whenever I run the docker container it terminates and gives Exited(3) as status
Sorry, what does that mean?
is the dockerfile inside of the backend folder?
no
It is, it should be outside of the folder
it is outside of the folder
Oh wait yeah it's dedented, kinda hard to see
oh nvm, it looked confusing
You guys probably need more info am I right?
Why are you expanding the backend and frontend into the app directory??? Just add them. Right now you're creating one folder with all the files from both folders.
Sorry, I literally just read like an hour of docker guides for a start, what am I doing wrong right now?
/* says "copy all files and folders"
So when you do backend/* you're adding everything in backend to /app not adding backend to /app
Do you not need the backend folder to run stuff?
yes, I do
Think of the docker container as another computer, add is copying files over to that computer.
Okay, will try!
ModuleNotFoundError: No module named 'backend'
[2023-03-14 16:00:44 +0000] [7] [INFO] Worker exiting (pid: 7)
[2023-03-14 16:00:45 +0000] [1] [INFO] Shutting down: Master
[2023-03-14 16:00:45 +0000] [1] [INFO] Reason: Worker failed to boot.
hmm
# syntax=docker/dockerfile:1
FROM python:3.10
WORKDIR /app
ADD backend/requirements.txt /app/
ADD backend/ /app/
ADD frontend/ /app/
RUN pip3 install -r requirements.txt
CMD ["gunicorn", "-b", "0.0.0.0:8000", "backend:app"]
Are you able to share your project so I can mess with it
/ between app shouldn't be problem here right?
yeah, how would you like it shared?
zip? github?
does gunicorn also run the frontend?
no, backend should serve my frontend
also i think u should move the pip3 install command right under the requirements.txt
so it will cache the installed packages
Try doing ADD backend backend/
not /app/backend/ ?
Working dir is already set to /app
dont u need a leading dot slash ./? or it works even without it
Yes gunicorn is running everything through the flask app
It should work without it
instead of ADD backend/ /app/?
Correct
From the docs for ADD
So it's necessary to create the directory on the destination
So doing ADD backend /app/ just dumps all the files into the /app directory
same error ;/
can u show your current dockerfile configuration?
# syntax=docker/dockerfile:1
FROM python:3.10
WORKDIR /app
ADD backend/requirements.txt /app/
ADD backend /backend
ADD frontend/ /app/
RUN pip3 install -r requirements.txt
CMD ["gunicorn", "-b", "0.0.0.0:8000", "backend:app"]
remove the leading slashes
You didn't copy the line I gave you correctly
cuz then it becomes absolute path
No leading slash
Must have a trailing slash
A leading slash will create a folder at the root of the file system. No leading slash will create the folder in WORKDIR.
A trailing slash tells Docker to create a folder. No trailing slash will tell Docker to create a file.
Failed to find attribute 'app' in 'backend'.
wait nvm, I can fix that
waiting game I guess
docker is pretty slow ngl
try this if u want faster build btw
`sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "None" to address: Name or service not known
(Background on this error at: https://sqlalche.me/e/14/e3q8)``
interesting
maybe this way it would be easier
How are you setting the database address?
this way:
app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{os.environ.get("DB_NAME")}'
is it because of .env-s?
docker must be able to access it from within the container
but backend/ folder has the .env in it
where is the db hosted?
The environment isn't inherited from your system. So you've gotta set the DB_NAME when you run the docker container
The DB address is set to None. Not an access issue
Please read the error messages
oh my bad
I dunno how flask loads that file
so, in the Dockerfile I do:
ENV environment-variable=something
for every one?
u can also use --env-file argument in the docker run command
when I run that from command line?
yea
sudo docker run -p 5000:5000 python-docker --env-file in the terminal
u need to specify the env file path for the env-file argument
So add backend/.env
ok so now i guess its an access issue
imma try with my local db
Wait, what is the DB name set to?
if it even works at the first place
127.0.0.1?
it's a real db in the cloud
Don't share that publicly. Anyone can access your db with that
I'm going to make a new one after this discussion anyways, I know that 🙂
?ssl=true looks like should be added to db url
Yes
didn't work :/, maybe I have to allow it from my service provider, brb
thought I had to add my ip address as one of the sources, but doesn't look like this is it
with that ssl=true:
invalid dsn: invalid connection option "ssl"
What did you change the database connection address to?
I added that ?ssl=true part at the end of the url
Odd
There seems to be a better way of doing this, but I haven't set up my database configuration that way up
Here they are using create_engine when connecting with the database, I'm not establishing the connection that way:/
https://docs.sqlalchemy.org/en/20/dialects/postgresql.html#ssl-connections:~:text=import ssl
ssl_context %3D ssl.create_default_context()
engine %3D sa.create_engine(
"postgresql%2Bpg8000%3A//scott%3Atiger%40192.168.0.199/test"%2C
connect_args%3D{"ssl_context"%3A ssl_context}%2C
)
flask is handling that for me
I don't understand why it doesn't require that ssl when I'm connecting to the db from my development app?
And I don't have blocked addresses
If the settings you had were correct, they should also be correct inside of Docker
Mar 14 07:05:25 PM [6410a955.3d209-1] user=[unknown],db=[unknown],app=[unknown],client=::1,LOG: connection received: host=::1 port=58042
Mar 14 07:05:25 PM [6410a955.3d209-2] user=postgres,db=postgres,app=[unknown],client=::1,LOG: connection authenticated: identity="postgres" method=md5 (/pgdata/dpg-cg716bo2qv28u2r3arig-a/pg_hba.conf:90)
Mar 14 07:05:25 PM [6410a955.3d209-3] user=postgres,db=postgres,app=[unknown],client=::1,LOG: connection authorized: user=postgres database=postgres application_name=psql SSL enabled (protocol=TLSv1.2, cipher=ECDHE-RSA-AES256-GCM-SHA384, bits=256)
Mar 14 07:05:25 PM [6410a955.3d209-4] user=postgres,db=postgres,app=psql,client=::1,LOG: disconnection: session time: 0:00:00.082 user=postgres database=postgres host=::1 port=58042
database logs
and then 10 seconds later
Mar 14 07:05:35 PM [6410a95f.3d218-2] user=postgres,db=postgres,app=[unknown],client=::1,LOG: connection authenticated: identity="postgres" method=md5 (/pgdata/dpg-cg716bo2qv28u2r3arig-a/pg_hba.conf:90)
Mar 14 07:05:35 PM [6410a95f.3d218-3] user=postgres,db=postgres,app=[unknown],client=::1,LOG: connection authorized: user=postgres database=postgres application_name=psql SSL enabled (protocol=TLSv1.2, cipher=ECDHE-RSA-AES256-GCM-SHA384, bits=256)
Mar 14 07:05:35 PM [6410a95f.3d218-4] user=postgres,db=postgres,app=psql,client=::1,LOG: disconnection: session time: 0:00:00.008 user=postgres database=postgres host=::1 port=49466```
@tidal sinew Out of ideas 😅 ?
Fine, Imma try to get dockerized version working at least with a local db then
Just remember the docker container is essentially a different computer. So the loopback address will point at it not your computer.
changed back to my local one, didn't fail this time 🙂
but, 0.0.0.0 refused to connect. when I try to access my app in web
more debugging I guess 🙂
0.0.0.0 is the local computer. So in a docker container it references that docker container, not your computer.
so, you want to say that this address is the wrong one?
Yes
You might be able to use the IP address of your computer on your network. I can't recall how docker sets up its network by default.
Localhost is the computer. So in a docker container it'll be the docker container.
Okay, so to be completely clear:
-p 8000:5000 part in the run command of docker forwards anything that's on that port in the docker container to my localhost. SO if in my Dockerfile I run the app this way: CMD ["gunicorn", "-b","0.0.0.0:8000", "backend:app"], then theoretically it should forward that port 8000 to port 5000 in my computer? Did I get it right?
Yes
so this shouldn't be happening?
I can imagine how annoyed you are of me, you'ld probably be thinking right now like "omfg how can't this guy just get it working lol, this isn't that hard".
Oh you've got the 8000 and 5000 backwards
if you look @ docker logs, is your application starting correctly?
do you mean those logs which get printed out after I run the run command?
rbr4t@rbr4t-Linux:~/yhiselamu-p2evik$ sudo docker run -p 5000:8000 --env-file backend/.env python-docker
[2023-03-14 17:44:43 +0000] [1] [INFO] Starting gunicorn 20.1.0
[2023-03-14 17:44:43 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)
[2023-03-14 17:44:43 +0000] [1] [INFO] Using worker: sync
[2023-03-14 17:44:43 +0000] [7] [INFO] Booting worker with pid: 7
if you try to do localhost:8000 do you see any new logs for attempted connections for example in docker?
Might be worth using docker exec to test if the server is working inside the container
wait, I need to go inside the docker now?
can u try doing -p 127.0.0.1:8000:5000 instead?
cuz if remember correctly, docker containers get their own local ip address
also first - does this work on your local machine outside docker
lol do you want to send me the project and I can save you from your suffering
that would be so nice
is github fine?
sure
@steady ravine no .env files tho, https://github.com/Rbr4t/flask-docker
getting it working that much that I can access that website would be highly appreciated
😢
and I pushed my secret keys to github directly
that's just fabolous!
Oooph haha
Nevermind, I deleted my last messages for no reason
rbr4t@rbr4t-Linux:~/yhiselamu-p2evik$ sudo docker run -p 5000:8000 --env-file backend/.env python-docker
[2023-03-14 17:44:43 +0000] [1] [INFO] Starting gunicorn 20.1.0
[2023-03-14 17:44:43 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)
[2023-03-14 17:44:43 +0000] [1] [INFO] Using worker: sync
[2023-03-14 17:44:43 +0000] [7] [INFO] Booting worker with pid: 7
You've changed the gunicorn port here. It's listening on 5000
Just set all the ports to 8000 and call it done lol. Gunicorn to 8000 and then -p 8000:8000
-p HOST_PORT:CONTAINER_PORT
I have tried every port combination, if it's the right one then it will just give me such screen:
I tried gunicorn outside of the container, there it works as expected
so that's not the cause
It must be the cause. Share your Dockerfile and share the command you're using to run it
I've not seen one example above where you've got the ports correct
# syntax=docker/dockerfile:1
FROM python:3.10
WORKDIR /app
ADD backend/requirements.txt /app/
ADD backend backend/
ADD frontend/ /app/
RUN pip3 install -r requirements.txt
CMD ["gunicorn", "-b","0.0.0.0:8000", "backend:app"]
# command line run: sudo docker run -p 8000:8000 --env-file backend/.env python-docker
# command line build: sudo docker build --tag python-docker .
Okay and then in your web browser go to http://localhost:8000
Make sure your local gunicorn isn't running still on port 8000
Well that's flask
That's what you expected to see?
that's what I was asking 🙂
You must have some magical abilities
IT'S NOT BLANK ANYMORE!!!!!!!!!!!!!!!
2023-03-14 18:26:56 +0000] [7] [INFO] Booting worker with pid: 7
[2023-03-14 18:27:36 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7)
[2023-03-14 18:27:36 +0000] [7] [INFO] Worker exiting (pid: 7)
[2023-03-14 18:27:36 +0000] [8] [INFO] Booting worker with pid: 8
should this be something to be worried about that [CRITICAL]?
Looks like something didn't close correctly so Gunicorn killed it
okay, imma try to connect my db again, maybe it just magically fixed itself????
🤣
nope -_-
maybe I should just try another database provider? how does that sound?
I don't even understand what the problem is, so I have no suggestions
back here now, I switched the db out that I would get docker working at least
sorry, went to get coffee
I got access to the website now, no need to inspect more
What error are you getting now?
qlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl"
Remove ssl?
and connection to server failed, port 5432 failed: FATAL: SSL/TLS required when I didn't add ssl
and I tried a couple others as well, but they all gave me some kind of errors 🙂
Apparently it's sslmode
That only happens when connecting from within the docker container, right?
I'm pretty sure I already tested that as well and it didn't work out for me.
but I can give it another try 🙂
maybe just maybe I mistyped or smh
You haven't given the line of code causing the error so I'm just guessing but googling around psycopg2 and ssl suggests it's sslmode='require'
i'm at work currently I can look after, but looks like kintec/zech are on the case
Would faster computer build docker containers faster?
Sorry I've only just seen this as I read the ping below it only. Does connecting to the database on render work if you run it on your PC? Just not in docker?
outside of docker it works like a charm
takes a bit of time to connect, like 2 seconds and then the app launces
So lets circle back to using what works outside of docker. What error message were you getting then? The SSL one or something different?
Outside of docker I didn't get any error message
But when you use whatever you used outside of docker inside docker, what error message do you get?
Like you shouldn't be having to change any code to get it to work inside docker
connection to server failed, port 5432 failed: FATAL: SSL/TLS inside the docker
That's the full error?
I can get you the whole error if you insist, but it's like really long
imma now have to build the app again so it takes a little time now
It's flask sqlalchemy that is being used
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Yeah I saw that after they linked the code 😅
You shouldn't have to build every time. Only when you want new changes to be available
changes to .env file require building every time, no?
FATAL: password authentication failed for user "'REDACTED"
I dunno if that's because of the SSL/TLS error or if one is causing the other but given it works outside docker and not insider docker it suggests it might be an environment variable issue again?
but the environment variables are the same in both docker and development?
if its being passed using --env-file then no
okay, good to know
For fun, can you hardcode the connection string in your python code?
No problem 😄
and then we'll get an answer, hopefully
@terse pier show me your dockerfile
There's likely something wrong if it's taking that long for code changes
# syntax=docker/dockerfile:1
FROM python:3.10
WORKDIR /app
ADD backend/requirements.txt /app/
ADD backend backend/
ADD frontend frontend/
RUN pip3 install -r requirements.txt
CMD ["gunicorn", "-b","0.0.0.0:8000", "backend:app"]
# command line run: sudo docker run -p 8000:8000 --env-file backend/.env python-docker
# command line build: sudo docker build --tag python-docker .
i already suggested moving the pip3
under the requirements.txt
Move the pip3 line above the backend line
Like giraffe started earlier
It'll cause the packages to be cached and code changes won't cause that layer to rerun
# syntax=docker/dockerfile:1
FROM python:3.10
WORKDIR /app
ADD backend/requirements.txt /app/
RUN pip3 install -r requirements.txt
ADD backend backend/
ADD frontend frontend/
CMD ["gunicorn", "-b","0.0.0.0:8000", "backend:app"]
# command line run: sudo docker run -p 8000:8000 --env-file backend/.env python-docker
# command line build: sudo docker build --tag python-docker .
So like that
bro, could that be the .env file that's been messing with me for like 1.5 hours now
because when I hardcoded it
it didn't return db errror
Does your app work?
yes, only the oauth doesn't
Probably because env file
but that's because it can't access the env contents
there was possible to declare those env files in Dockerfile yeah?
I've just been having a look at the docker docs on --env-file. Can you try changing your command to
sudo docker run -p 8000:8000 --env-file ./backend/.env python-docker
https://docs.docker.com/engine/reference/commandline/run/#env here for reference
I can't think why the ./ would be any different to backend/.env but worth a try maybe
no, that doesn't change anything, I'm pretty sure I tested it before
and it looks like this is the case
I guess I've to do it like so:
https://phoenixnap.com/kb/docker-environment-variables#:~:text=Set ENV Values,Docker Compose.
aka straight to the dockerfile
That defeats the whole point. You don't wanna do that. Can you share what your .env contains but change the values to nonsense?
SECRET_KEY="REEEEEEEEEEEEE"
SECRET_KEY_TEST="REEEEEEEEEEEEE"
CLIENT_ID="REEEEEEEEEEEEE"
CLIENT_ID_TEST="REEEEEEEEEEEEE"
DB_SECRET_KEY="REEEEEEEEEEEEE"
DB_NAME='REEEEEEEEEEEEE'
Try remove the "
something's off, it fails even when the env variable is in the Dockerfile
does it matter?
The docker docs don't include it so maybe...
hmm, now it doesn't say that there is no OAuth client when I browse that far
so it seems like this actually did impact
Did it connect to the database?
yes
Using the .env file only?
yes
kinda, now I gotta somehow get google OAuth working properly
whenever I try to get there it just keeps loading
After you login or?
okay, this is just really slow
I now got to that account choosing panel, but it takes forever for website to load
Does it eventually load?
hasn't been able to do it yet
but if it were the keys, it would have given me the error straight away
I dunno if it'll make a difference but are you using the same port as when you were running it outside docker? If so. Can you try incognito?
same port, tried on firefox already, same problem
It's when it's trying to load the callback URL?
What's your callback url and what url are you using to access the site in the first place?
I know why it's failing
You got a fix?
@auth.route('/login', methods=['GET'])
def login():
redirect_uri = "http://localhost:5000/callback"
return oauth.google.authorize_redirect(redirect_uri)
this is my login route
could it be the redirect_uri
?
What url are you accessing the site with?
If it's not http://localhost:5000 then yes probably
the google site?
Nah your site, what do you put in your browser to get to the login page?
/login
The full thing 😄
Not your code. So you have done docker run then you go to your browser and you type something in the URL bar to access your site. What do you type?
localhost:8000
Okay then your callback should be http://localhost:8000/callback
Do you have to register it in the google dev console?
I think you have to set the callback there right?
Yeah that's probably easier. Make sure you change your docker run to do -p 5000:8000
yes sir
Something for later once we have this working. But you'll need to "fix" the callback thing when you deploy. So if your site is like http://rbr4tsawesomesite.render.com you'll need to use that for your callback
Are you still running your local version? None docker?
i'm not running local version
What's the output of docker ps?
no applications running
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
I could do a restart to my pc
probably the easiest 🤣
What's the output of sudo netstat -ano -p tcp
even if something is running somewhere
wait, I have to install it first
yeah, too much data to handle
yeah, something is running
on that port
tcp 19 0 0.0.0.0:5000 0.0.0.0:* LISTEN 41554/python3
how can I kill it 🔪
Oh it might be because gunicorn is spawning them lol
Maybe
Yeah restart
Or ps aux | grep gunicorn
Then kill that pid
I guess you already restarted 😅
yeah, I did
now my accessing localhost takes ages
and Access blocked: Authorization Error
Where's that error coming from?
I don't know, it doesn't log anything
Is it displayed on your webpage?
You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure.
This might be where you need to use a different browser, clear your cache or use incognito
If your "local" non-docker version was running on port 5000
okay, I built it again, and now doesn't throw me this error anymore
and boom!
working!!!!!!!!!!!!

🤩
docker locally now working
time to deploy it online 😈
gotta change that uri tho first
While you were rebuilding I was googling the error https://developers.google.com/identity/protocols/oauth2/production-readiness/policy-compliance
This says you probably need a different project for production and there are some other criteria
Or maybe since it's for school you could just leave it as a testing project
Okay cool 🙂 Good luck!
I should use flask's url_for() for that /login redirect
It's been so long since I used flask I can't remember what that does 😅
Gets the URL from a route name
Ah that's handy. Can it be used in templates too?
I think so
I've never actually used Flask, so I could be wrong about that...
It just makes sense to have it available in templates
Is it when it needs to hit the database?
no, when I need to access some url-s
Do those URLs access the database though? Accessing a database across the internet will cause some slowdown
feels like this error is given randomly:You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure.
no, those are other ones
Check that link above. You might need to create the project again. It seems there are some rules you need to follow to be compliant
like /login, /homepage
I'm not sure then
weird
I haven't tested the db part yet, so we'll see
😬
I wish docker would show me logs not only when some kind of error hits
Logs of what?
like print()s and stuff like this into the console
okay, got it working, it needed _exteranl=True parameter with that url_for()
database works as expected, no problems with that
did we really just got Docker working on my computer?
Are you able to see those when running outside of Docker?
With the docker container running, run docker logs ID_OF_CONTAINER
I think you can get the container ID with docker ps
I open a new terminal and do that there yeah?
Yeah
okay, I was expecting it to run in real time not to print out once, but thx for that
Only thing what I don't quite like is that it takes quite some time to query data from the database
but the service did warn about that
ok, that could have been easily googleable thing, but thx still
Now, Imma have a little break, eat smh and then I'm going to deploy it
ok, back imma now start suffering again
my app should have runtime of something else than python3 yeah?
docker or something?
nvm, found it
I'm hackerman now
nah, not really
build did succeed, but my application has no frontend
well shit
shouldn't docker be universal, when it works in one place it should always work in other places too, am I right?
well, shit 2x
Yes it should
well shit 3x
any idea how to get frontend to my application?
I and Zech ran into the same problem yesterday when I hosted it straight from my repo
but that time I couldn't get frontend locally either working
Does it find them locally now when you run it exactly how you run it in the docker?
yes
So you're running it from the folder that has the frontend and backend folders in it? Or are you running it from the backend folder?
both are in it
it's the docker file
could ' strict-origin-when-cross-origin' have to do something with it?
What do you see when you try to access the frontend using docker?
like when I go there in the url?
Yes
That's the HTML
oh, yeah
Here, get rid of the ../ do the same a few lines down
That's assuming you're running from within the backend folder. You're not.
uhm, now it completely broke
How so
File system???
Did you get an error in the flask logs?
Something is very wrong and I don't know what. Change the main function in views.py to return "Hello World" just to see if it works at all.
no hello world either
Ok in your dunder init don't register the auth and func views just to make sure they're not messing stuff up
Didn't you change your port to 5000 because that's what your callback was set to in Google dev?
This is the home page. Not auth.
Trying to get the frontend to load.
The views.py views not the auth.py views.
not important right now, we have no frontend
It's important if your server is listening on port 5000, not 8000 but I'll stay out of it. Good luck!
Yeah but this was working 5 seconds ago to send 404's now it's not even doing that
Dunno why the port would have changed in that time
This one you went to a different URL than in the previous screenshot, why?
oh, you mean why did I not try to access http://127.0.0.1:5000/frontend/src?
this time
Yeah
I'm not sure, but that didn't yield me any results either
That was port 8000 though not 5000
I changed that halfway through, but that doesn't matter
What port is docker using, let's figure that out? You keep using two different ones and it's a problem.
CMD ["gunicorn", "backend:app"]
not port specified
for some reason I needed it for Render to work properly
What is docker run using
sudo docker run -p 8000:8000 --env-file backend/.env python-docker
Ok so 8000 not 5000
You will not be able to access the site on 5000 if that's how you're running the site
okay, yeah, looks like I caused it
Hi World appeared when I fized it in the Dockerfile
Ok. Now put it back to sending from the directory.
back here
idk if that helps, but when I print out the path here:
@views.route("/<path:path>")
def home(path):
print(path)
return send_from_directory('frontend/public', path)
it's the one in the url
I guess mixing multiple human languages in one code wasn't a good idea
😅 for readabilty
What happens if you go to the home page
Did you get any errors in the docker logs when loading that page?
no
Ok put it back to the way it was and show me what the code is
@views.route('/', methods=['GET'])
def main():
return send_from_directory('frontend/public', 'index.html')
# static files, JS, CSS etc
@views.route('/<path:path>')
def home(path):
print(path)
return send_from_directory('frontend/public', path)
Ok get rid of the ../
Let's try to only change one thing at a time. So always use the same URL unless we decide to change it.
yes yes, I was with without those ../ the whole time, I thought you wanted to go back all the way lol
I know it sounds scuffed, but I could give you access to my pc via some software if you feel like you have to test some stuff out yourself.
So it doesn't work with and without the ../?
with ../ the frontend is there, but when I try to navigate to that folder via URL it breaks
Ok well that was useful information
without ../ there is no frontend before and after I navigate
Going to http://127.0.0.1:8000/ works when you use ../frontend/public?
yes
Ok so what URL doesn't work?
when you are any of those directories after the slash
Give me a URL
http://127.0.0.1:8000/frontend/src for example
What file should that show?
routes folder and 2 js scripts
The path is being appended to the path you have to send_from_directory. So going to http://127.0.0.1:8000/frontend/src will attempt to find a file at the path ../frontend/public/frontend/src
Which doesn't exist
of
oh
okay, but when I go to http://127.0.0.1:8000/src nothing happens
still
even when I took away ../ from those routes
Leave the ../ flask is using magic to make that work and it won't work otherwise.
When you go to /src it's looking for a file at ../frontend/public/src
It's looking in the folder you told it to look in
which does not exist according to flask, because all I'm getting is that damn Not Found message
It doesn't exist. frontend/src exists but you're telling it to look in frontend/public not frontend
so if I would do http://127.0.0.1:8000/../src it would go one directory back and then src/ would be accessable in theory?
No
There's nothing useful in the src directory anyways... Why are you trying to access it?
just for demonstration purposes????
There's nothing there to load. It's a svelte project, the browser doesn't understand svelte. I'm assuming it was built into what you have in frontend/public/build
yes, the build files should be there indeed
Sorry, but does this shitstorm mean that I have built and app what you can't deploy?
If you wanna load something different go to http://127.0.0.1:8000/diary.png
I'm assuming your svelte app is running from index.html? No?
I don't know how Svelte works exactly, but this is what index.html looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Puudumispäevik</title>
<link rel='icon' type='image/png' href='/diary.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>
</head>
<body>
</body>
</html>
Does going to http://127.0.0.1:8000 show your svelte app?
yes
Ok. I'm assuming the router is what's not working, correct?
at this point I'm not even sure anymore
I think you need to do two things to make this work.
-
create a route in flask that uses an assets folder for all your images, CSS, and js files.
-
change the home route in views.py to send the index.html file so that your svelte app is loaded on all routes that flask isn't using.
okay, so for 1) it would essentially be eternity of the public folder?
So
- create a folder in frontend named
assets - copy the home route in views.py and change it to use the path
../frontend/assets - move your images, CSS, and js to that folder
- update all the URLs in your HTML/js to use the assets route for images/js/CSS.
Then finally change the home route in views.py to not use the path variable and instead just use the string "index.html". It'll be the same as the main route.
index.html is your svelte app, so in order for it to be used you have to send it.
okay html file like so
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Puudumispäevik</title>
<link rel='icon' type='image/png' href='/diary.png'>
<link rel='stylesheet' href='../assets/global.css'>
<link rel='stylesheet' href='../assets//bundle.css'>
<script defer src='../assets/bundle.js'></script>
</head>
<body>
</body>
</html>
assets directory like so:
so that only index.html remains in public/ directory?
Yeah
Trying to isolate everything onto individual routes so that we can send everything else to svelte
@views.route('/', methods=['GET'])
def main():
return send_from_directory('../frontend/assets', "index.html")
# static files, JS, CSS etc
@views.route('/<path:path>')
def home(path):
return send_from_directory('../frontend/public', "index.html")
I said to add a new route for assets. You must leave the main route the way it was. index.html is your svelte app, so anywhere you want to access it you must send it.
sorry, I'm starting to lose it, when did you give me such instruction?
Point 2
The new assets route will work exactly like the home route except it'll use the assets folder not the public folder
@views.route('/', methods=['GET'])
def main():
return send_from_directory('../frontend/assets', "index.html")
@views.route('/assets/<path:path>')
def emoh(path):
return send_from_directory('../frontend/assets', path)
@views.route('/<path:path>')
def home(path):
return send_from_directory('../frontend/public', "index.html")
?
Rename the assets route to have a different function name
Oh and change the path for it to '/assets/<path:path>'
like so?
Yep
Now make sure all the images, CSS, and js are moved to your assets folder
And make sure all the URLs to the images, CSS, and js in your HTML and svelte app are updated to be in the assets folder
I have no idea why my internet has fell into coma
Lol
okie dokie, it should be there lol
That needs to use public not assets, only emoh should use assets
Did you update the HTML to load it from /assets/bundle.css
You moved it to a new folder, so the HTML needs to be updated to match
<link rel='stylesheet' href='../assets//bundle.css'>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Puudumispäevik</title>
<link rel='icon' type='image/png' href='/diary.png'>
<link rel='stylesheet' href='../assets/global.css'>
<link rel='stylesheet' href='../assets//bundle.css'>
<script defer src='../assets/bundle.js'></script>
</head>
<body>
</body>
</html>
bruh
//
finally
It's almost 2 am
more than 7 hours of coding for me
Why do you have the ..?
The route is at the root of your site so just do /assets/file.ext
route aka index?
uhm, this is still in my public folder???
and assets is outside public folder
so I must first move out of it
before I can access assets/ folder
No
but it works
Any URL that starts with / will be at the root of your site and not relative to the current page URL
It does but it could break
The correct way to do it is /assets
okie dokie
<link rel='stylesheet' href='/assets/global.css'>
<link rel='stylesheet' href='/assets/bundle.css'>
<script defer src='/assets/bundle.js'></script>
looks like so
Yay!
imma try to deploy it
You might need to hard refresh pages since you moved assets to a new folder
Usually pressing shift while reloading the page to clear the browser cache
if you refresh and look under networking tab it's pretty wild
Is it working?
not really
What's wrong with it
when you refresh the site, it alternates between Bad Gateway, the site it's supposed to look, the site with only HTML and the site with some CSS but it's clearly missing a lo
I can't function anymore, coffee has stopped working, good evening!
Fwiw you only need to hard refresh once after uploading the changes
Okay, that might have been my crappy internet connection
Okay, last time before I close this issue, could you give me a bit more brief explanation on how do these routes work, because when I will open this project in the future I will have probably already forgotten how it works. This would be kinda like a documentation for this code snippet.
# homepage
@views.route('/', methods=['GET'])
def main():
return send_from_directory('../frontend/public', "index.html")
# what was this snippet's purpose again?
@views.route('/assets/<path:path>')
def emoh(path):
return send_from_directory('../frontend/assets', path)
# all routes that flask isn't using are being served svelte app
@views.route('/<path:path>')
def home(path):
return send_from_directory('../frontend/public', "index.html")
Anyway, for the most part the application is running, I fixed google OAuth issue, it just required updating Authorized redirect URIs in google console.
Using http://localhost as the example
http://localhost/ will serve ../frontend/public/index.html
http://localhost/assets/styles/style.css would serve ../frontend/assets/styles/some_file.css as an example
http://localhost/any/other/path would serve ../frontend/public/index.html as the comment says, this will basically have the effect of sending all other routes to svelte to be handled by it and it's router
So basically / is svelte
/assets/ is anything in the assets folder
Any other route will be sent to svelte and it's router will handle whatever route it is given
okay, imma add those much needed comments
Zech can probably provide a more concise answer but that's the general idea of it 😅
Either way, thank you both so much, I wouldn't been able to solve it on my own 🙂 . Even though I didn't understand all of it, it was a good learning experience and I'm much more comfortable with deploying now on. I just can't thank you guys enough for it 🙂
