├── .idea
├── .gitignore
├── inspectionProfiles
│ └── profiles_settings.xml
├── integration_with_sqlalchemy.iml
├── misc.xml
└── modules.xml
├── README.txt
├── integrationWithMongoDB
├── pyMongoApplication.py
└── secondFilePyMogo.py
└── integrationWithSQL
├── :memory
├── sqlAlchemyApplication.py
└── sqlAlchemyCoreApplication.py
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/integration_with_sqlalchemy.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/README.txt:
--------------------------------------------------------------------------------
1 | # integration_with_python
2 |
3 | Projeto de Integração com Banco de Dados SQL e NoSQL em Python
4 |
5 | O uso de banco de dados permeia diversos âmbitos da computação. Por esse motivo realizar integração das
6 | aplicações, em diferentes linguagens de programação, e banco de dados se torna de suma importância. Este projeto possui duas
7 | partes bem definidas. Na primeira parte iremos utilizar integração com banco de dados relacional, enquanto que na segunda parte
8 | iremos entrar no mundo dos não relacionais orientados a documentos.
9 |
10 | Parte 1 - integrationWithSQL
11 |
12 | Nesta parte nosso projeto está focado na utilização do SQLAlchemy para criação de um esquema simples dentro do SQlite. Adotamos
13 | o SQlite como opção de banco de dados para simplificação do setup. Sendo assim nesta estapa utilizaremos dois modelos
14 | disponibilizados pelo framework:
15 |
16 | -> ORM
17 | -> CORE
18 |
19 | O ORM - Object Relational Mapping - consiste em um modelo orientado a domínio onde não estaremos lidando com a linguagem de
20 | consulta de banco de dados - SQL - diretamente. O ORM realiza o mapeamento entre o mundo relacional e orientação à objeto.
21 | Em sentido contrário, o CORE estará disponibilizando o acesso direto ao SQL. Sendo assim, diferentemente do ORM este modelo
22 | é orientado a esquema (foco no SQL).
23 |
24 | Parte 2 - integrationWithMongo
25 |
26 | Utilizaremos o módulo pymongo criado e mantido pela equipe de Python do MongoDB. Sendo assim, iremos criar o banco de dados,
27 | coleções, documentos utilizando o pymongo em conjunto com MongoDb Atlas. As configurações para acesso do cluster estão
28 | definidas dentro da aplicação.
29 |
--------------------------------------------------------------------------------
/integrationWithMongoDB/pyMongoApplication.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import pprint
3 |
4 | import pymongo as pyM
5 |
6 | client = pyM.MongoClient("mongodb+srv://mongo:senha@cluster.yoczfda.mongodb.net/?retryWrites=true&w=majority")
7 |
8 | db = client.test
9 | collection = db.test_collection
10 | print(db.test_collection)
11 |
12 | # definição de infor para compor o doc
13 | post = {
14 | "author": "Mike",
15 | "text": "My first mongodb application based on python",
16 | "tags": ["mongodb", "python3", "pymongo"],
17 | "date": datetime.datetime.utcnow()
18 | }
19 |
20 | # preparando para submeter as infos
21 | posts = db.posts
22 | post_id = posts.insert_one(post).inserted_id
23 | print(post_id)
24 |
25 | # print(db.posts.find_one())
26 | pprint.pprint(db.posts.find_one())
27 |
28 | #bulk inserts
29 | new_posts = [{
30 | "author": "Mike",
31 | "text": "Another post",
32 | "tags": ["bulk", "post", "insert"],
33 | "date": datetime.datetime.utcnow()},
34 | {
35 | "author": "Joao",
36 | "text": "Post from Joao. New post available",
37 | "title": "Mongo is fun",
38 | "date": datetime.datetime(2009, 11, 10, 10, 45)}]
39 |
40 | result = posts.insert_many(new_posts)
41 | print(result.inserted_ids)
42 |
43 | print("\nRecuperação final")
44 | pprint.pprint(db.posts.find_one({"author": "Joao"}))
45 |
46 | print("\n Documentos presentes na coleção posts")
47 | for post in posts.find():
48 | pprint.pprint(post)
49 |
50 |
--------------------------------------------------------------------------------
/integrationWithMongoDB/secondFilePyMogo.py:
--------------------------------------------------------------------------------
1 | import pprint
2 |
3 | import pymongo
4 | import pymongo as pyM
5 |
6 | client = pyM.MongoClient("mongodb+srv://mongo:senha@cluster.yoczfda.mongodb.net/?retryWrites=true&w=majority")
7 | db = client.test
8 | posts = db.posts
9 |
10 | for post in posts.find():
11 | pprint.pprint(post)
12 |
13 | print(posts.count_documents({}))
14 | print(posts.count_documents({"author": "Mike"}))
15 | print(posts.count_documents({"tags": "insert"}))
16 |
17 | pprint.pprint(posts.find_one({"tags": "insert"}))
18 |
19 | print("\nRecuperando info da coleção post de maneira ordenada")
20 | for post in posts.find({}).sort("date"):
21 | pprint.pprint(post)
22 |
23 | result = db.profiles.create_index([('author', pymongo.ASCENDING)],
24 | unique=True)
25 | print(sorted(list(db.profiles.index_information())))
26 |
27 | user_profile_user = [
28 | {'user_id': 211, 'name': 'Luke'},
29 | {'user_id': 212, 'name': 'Joao'}]
30 |
31 | result = db.profile_user.insert_many(user_profile_user)
32 |
33 | print("\nColeções armazenadas no mongoDB")
34 | collections = db.list_collection_names()
35 |
36 | # db['profiles'].drop()
37 |
38 | for collection in collections:
39 | print(collection)
40 |
41 | for post in posts.find():
42 | pprint.pprint(post)
43 |
44 | # print(posts.delete_one({"author": "Mike"}))
45 | # print(db.profile_user.drop())
46 |
47 | client.drop_database('test')
48 |
49 | print(db.list_collection_names())
50 |
--------------------------------------------------------------------------------
/integrationWithSQL/:memory:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/julianazanelatto/integration_python_database/b46d3b569eb6df1ed31312b112867a70e0fd3f70/integrationWithSQL/:memory
--------------------------------------------------------------------------------
/integrationWithSQL/sqlAlchemyApplication.py:
--------------------------------------------------------------------------------
1 | """
2 | Primeiro programa de integração com banco de dados
3 | utilizando SQLAlchemy e modelo ORM
4 |
5 | """
6 | from sqlalchemy.orm import declarative_base
7 | from sqlalchemy.orm import Session
8 | from sqlalchemy.orm import relationship
9 | from sqlalchemy import Column
10 | from sqlalchemy import create_engine
11 | from sqlalchemy import inspect
12 | from sqlalchemy import select
13 | from sqlalchemy import func
14 | from sqlalchemy import Integer
15 | from sqlalchemy import String
16 | from sqlalchemy import ForeignKey
17 |
18 | Base = declarative_base()
19 |
20 |
21 | class User(Base):
22 | """
23 | Esta classe representa a tabela user_account dentro
24 | do SQlite.
25 | """
26 | __tablename__ = "user_account"
27 | # atributos
28 | id = Column(Integer, primary_key=True)
29 | name = Column(String)
30 | fullname = Column(String)
31 |
32 | address = relationship(
33 | "Address", back_populates="user", cascade="all, delete-orphan"
34 | )
35 |
36 | def __repr__(self):
37 | return f"User(id={self.id}, name={self.name}, fullname={self.fullname})"
38 |
39 |
40 | class Address(Base):
41 | __tablename__ = "address"
42 | id = Column(Integer, primary_key=True)
43 | email_address = Column(String(30), nullable=False)
44 | user_id = Column(Integer, ForeignKey("user_account.id"), nullable=False)
45 |
46 | user = relationship("User", back_populates="address")
47 |
48 | def __repr__(self):
49 | return f"Address(id={self.id}, email_address={self.email_address})"
50 |
51 |
52 | print(User.__tablename__)
53 | print(Address.__tablename__)
54 |
55 | # conexão com o banco de dados
56 | engine = create_engine("sqlite://")
57 |
58 | # criando as classes como tabelas no banco de dados
59 | Base.metadata.create_all(engine)
60 |
61 | # depreciado - será removido em futuro release
62 | # print(engine.table_names())
63 |
64 | # investiga o esquema de banco de dados
65 | inspetor_engine = inspect(engine)
66 | print(inspetor_engine.has_table("user_account"))
67 | print(inspetor_engine.get_table_names())
68 | print(inspetor_engine.default_schema_name)
69 |
70 | with Session(engine) as session:
71 | juliana = User(
72 | name='juliana',
73 | fullname='Juliana Mascarenhas',
74 | address=[Address(email_address='julianam@email.com')]
75 | )
76 |
77 | sandy = User(
78 | name='sandy',
79 | fullname='Sandy Cardoso',
80 | address=[Address(email_address='sandy@email.br'),
81 | Address(email_address='sandyc@email.org')]
82 | )
83 |
84 | patrick = User(name='patrick', fullname='Patrick Cardoso')
85 |
86 | # enviando para o BD (persitência de dados)
87 | session.add_all([juliana, sandy, patrick])
88 |
89 | session.commit()
90 |
91 | stmt = select(User).where(User.name.in_(["juliana", 'sandy']))
92 | print('Recuperando usuários a partir de condição de filtragem')
93 | for user in session.scalars(stmt):
94 | print(user)
95 |
96 | stmt_address = select(Address).where(Address.user_id.in_([2]))
97 | print('\nRecuperando os endereços de email de Sandy')
98 | for address in session.scalars(stmt_address):
99 | print(address)
100 |
101 |
102 | stmt_order = select(User).order_by(User.fullname.desc())
103 | print("\nRecuperando info de maneira ordenada")
104 | for result in session.scalars(stmt_order):
105 | print(result)
106 |
107 | stmt_join = select(User.fullname, Address.email_address).join_from(Address, User)
108 | print("\n")
109 | for result in session.scalars(stmt_join):
110 | print(result)
111 |
112 | # print(select(User.fullname, Address.email_address).join_from(Address, User))
113 |
114 | connection = engine.connect()
115 | results = connection.execute(stmt_join).fetchall()
116 | print("\nExecutando statement a partir da connection")
117 | for result in results:
118 | print(result)
119 |
120 | stmt_count = select(func.count('*')).select_from(User)
121 | print('\nTotal de instâncias em User')
122 | for result in session.scalars(stmt_count):
123 | print(result)
124 |
125 | # encerrando de fato a session
126 | session.close()
127 |
--------------------------------------------------------------------------------
/integrationWithSQL/sqlAlchemyCoreApplication.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import create_engine, text
2 | from sqlalchemy import ForeignKey
3 | from sqlalchemy import MetaData
4 | from sqlalchemy import Table
5 | from sqlalchemy import Column
6 | from sqlalchemy import Integer
7 | from sqlalchemy import String
8 |
9 | engine = create_engine('sqlite:///:memory')
10 |
11 | metadata_obj = MetaData()
12 | user = Table(
13 | 'user',
14 | metadata_obj,
15 | Column('user_id', Integer, primary_key=True),
16 | Column('user_name', String(40), nullable=False),
17 | Column('email_address', String(60)),
18 | Column('nickname', String(50), nullable=False),
19 | )
20 |
21 | user_prefs = Table(
22 | 'user_prefs', metadata_obj,
23 | Column('pref_id', Integer, primary_key=True),
24 | Column('user_id', Integer, ForeignKey("user.user_id"), nullable=False),
25 | Column('pref_name', String(40), nullable=False),
26 | Column('pref_value', String(100))
27 | )
28 |
29 | print("\nInfo da tabela users")
30 | print(user_prefs.primary_key)
31 | print(user_prefs.constraints)
32 |
33 | print(metadata_obj.tables)
34 |
35 | for table in metadata_obj.sorted_tables:
36 | print(table)
37 |
38 | metadata_obj.create_all(engine)
39 |
40 | metadata_bd_obj = MetaData()
41 | financial_info = Table(
42 | 'financial_info',
43 | metadata_bd_obj,
44 | Column('id', Integer, primary_key=True),
45 | Column('value', String(100), nullable=False),
46 | )
47 |
48 | # inserindo info na tabela user
49 | sql_insert = text("insert into user values(2,'Maria','email@email.com','Ma')")
50 | engine.execute(sql_insert)
51 |
52 | print("\nInfo da tabela financial_info")
53 | print(financial_info.primary_key)
54 | print(financial_info.constraints)
55 |
56 | print('\nExecutando statement sql')
57 | sql = text('select * from user')
58 |
59 | result = engine.execute(sql)
60 | for row in result:
61 | print(row)
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------