Hi, I’m a student with the Code Institute and I’m wondering whether the code I have written is acceptable to connect my website to the internal postgres database. The website deployed fine (address below) - I’m using Python Flask, HTML and CSS.
I have yet to try and deploy what I’ve written for the 2 files app.py and env.py which are shown on the attached screenshot and below. The app.py works fine (without the database add-ons) and the env.py would be a secret file with database values (not included!). I have added the code below for env.py as I can’t use 2 embedded images. I am worried about this syntax in app.py and don’t know if I need the ‘app.config’ part:
app.config[“RENDER_HOST”] = os.environ.get(“RENDER_HOST”)
Any advice would be welcome as this is part of a project I have to submit. My college is nervous about using anything but Heroku and therefore doesn’t provide help with other providers.
The database connection string is provided by the database dashboard. The “Internal Database URL”. The most common pattern is to take that value and set it as a DATABASE_URL environment variable on your web service (“Environment” tab). More in the docs: PostgreSQL | Render · Cloud Hosting for Developers
You’d then reference the DATABASE_URL in psycopg2, e.g.:
Thankyou for your reply, please forgive my ignorance. A couple of questions:
i) what values should I put in the env.py hidden file which is needed to contain passwords and secret keys and so forth? In the coding I wrote, I left out those values which obviously I don’t want people to see. Do I need env.py if I have a Render environment?
ii) Is this all I need on the app.py if I have the environment setup (which I’ll do presently)?
i) I’m not a Python expert, I’m not sure what you mean by “hidden file”, env.py, is that like a dotenv file? It’s best practice not to have any passwords committed into your repo, and to set them as environment variables. In Render terms, that would be in the “Environment” tab of the service, as standard “Environment Variables”, or a “Secret File” can be added to your instance.
ii) I think that’s all you need to establish a database connection (as long as you’re importing the required packages). You would then use the connection to query the database.