ORM Frameworks (SQLAlchemy)
- Generally for interacting with databases, we use SQL Refer Here for sql tutorial in Postgres
- ORM (Object Relational mapping) Frameworks, helps mapping tables to Objects and developers need not have to code anything specific to a database (SQL Server, Oracle, Postgres, mysql)
- We create Mappings (Table to Class), to insert,query,update, delete we will be dealing with objects not sql queries
- In python, SQL Alchemy is one of the popular ORM Frameworks and we will try using SQL Alchemy in our fast api project to deal with library Refer Here
Lets add the database to our api
- Activate virtual environment in library and install the following packages
pip install SQLAlchemy
pip install psycopg2
- Refer Here for documentation
- Lets try reading all the necessary config from environmental variables and also create a file to have defaults
To use the python-dotenv package in your Python projects for managing environment variables, follow these steps:
Step 1: Install the Package
First, you need to install the python-dotenv package. You can do this using pip:
pip install python-dotenv
Step 2: Create a .env File
Next, create a .env file in the root directory of your project. This file will contain your environment variables in the format KEY=VALUE. For example:
DEBUG=True
SECRET_KEY=mysecretkey
DATABASE_URL=postgresql://user:password@localhost:5432/mydatabase
Step 3: Load Environment Variables in Your Script
In your Python script, you will need to import the load_dotenv function from the dotenv module and call it to load the variables from the .env file into your environment. Here’s how you can do that:
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Access your environment variables using os.getenv
debug = os.getenv('DEBUG')
secret_key = os.getenv('SECRET_KEY')
database_url = os.getenv('DATABASE_URL')
print(f"Debug: {debug}\nSecret Key: {secret_key}\nDatabase URL: {database_url}")
Explanation
-
Importing Libraries: You import the
osmodule to access environment variables and theload_dotenvfunction to load them. -
Loading Variables: The
load_dotenv()function reads the.envfile and loads the variables intoos.environ. -
Accessing Variables: You can access the environment variables using
os.getenv('VARIABLE_NAME').
Best Practices
-
Keep the
.envFile Secure: Since the.envfile may contain sensitive information, add it to your.gitignorefile to prevent it from being tracked by version control systems. -
Use Different
.envFiles for Different Environments: You can create multiple.envfiles (e.g.,.env.dev,.env.prod) and load the appropriate one based on the environment your application is running in. -
Default Values: You can provide default values for environment variables using
os.getenv('VARIABLE_NAME', 'default_value'), which will be used if the variable is not found.
By following these steps, you can effectively manage environment variables in your Python applications using the python-dotenv package, keeping your configurations clean and secure[1][2][3].
- Refer Here for changes done to create an api which stores the details in postgres database
- Lets run this project on linux instance
- Watch classroom video for steps
Sending API requests from python code
import requests
#https://api.geoapify.com/v2/place-details?lat=17.437503884930734&lon=78.44849970639234&apiKey=23d02484df7f4f66b09785e7b6510c28
BASE_URL = "https://api.geoapify.com/v2/place-details"
API_KEY = "23d02484df7f4f66b09785e7b6510c28"
lat = 17.437503884930734
lon = 78.44849970639234
response = requests.get(f"{BASE_URL}?lat={lat}&lon={lon}&apiKey={API_KEY}")
if response.status_code == 200:
data = response.json()
print(data)
- Exercise: Write a python code to send requests to create, update and delete books by running books api on the linux machine in any cloud
