@@ -444,6 +444,50 @@ Base = declarative_base()
444444To learn more about integrating a database into your FastAPI application,
445445follow along the [ FastAPI SQL Database guide] ( https://fastapi.tiangolo.com/tutorial/sql-databases/#create-the-database-models ) .
446446
447+ #### Django
448+
449+ [ Django] ( https://djangoproject.com ) is a high-level Python web framework that
450+ encourages rapid development and clean, pragmatic design.
451+
452+ To use the Cloud SQL Connector with Django, you need to create a custom database
453+ backend which subclasses the existing MySQL backend. (Note, at present Postgres
454+ is not supported because Django requires the psycopg2 driver, which is not
455+ currently compatible with the connector.)
456+
457+ Create a ` cloudsql ` directory in your project with a blank ` __init__.py ` and a
458+ ` base.py ` containing the following code:
459+
460+ ``` python
461+ from django.db.backends.mysql import base
462+ from google.cloud.sql.connector import Connector
463+
464+
465+ class DatabaseWrapper (base .DatabaseWrapper ):
466+ def get_new_connection (self , conn_params ):
467+ return Connector().connect(** conn_params)
468+ ```
469+
470+ Then in your settings.py file, set your ` DATABASES ` setting as follows:
471+
472+ ``` python
473+ DATABASES = {
474+ " default" : {
475+ " ENGINE" : " cloudsql" ,
476+ " USER" : " ..." ,
477+ " PASSWORD" : " ..." ,
478+ " NAME" : " ..." ,
479+ " OPTIONS" : {
480+ " driver" : " pymysql" ,
481+ " instance_connection_string" : " project:region:instance"
482+ }
483+ }
484+
485+ # Needed because Django does not support PyMySQL out of the box
486+ import pymysql
487+ pymysql.install_as_MySQLdb()
488+ ```
489+
490+
447491# ## Async Driver Usage
448492
449493The Cloud SQL Connector is compatible with
0 commit comments