Discover how a bimodal integration strategy can address the major data management challenges facing your organization today.
Get the Report →How to use SQLAlchemy ORM to access Bitbucket Data in Python
Create Python applications and scripts that use SQLAlchemy Object-Relational Mappings of Bitbucket data.
The rich ecosystem of Python modules lets you get to work quickly and integrate your systems effectively. With the CData Python Connector for Bitbucket and the SQLAlchemy toolkit, you can build Bitbucket-connected Python applications and scripts. This article shows how to use SQLAlchemy to connect to Bitbucket data to query, update, delete, and insert Bitbucket data.
With built-in optimized data processing, the CData Python Connector offers unmatched performance for interacting with live Bitbucket data in Python. When you issue complex SQL queries from Bitbucket, the CData Connector pushes supported SQL operations, like filters and aggregations, directly to Bitbucket and utilizes the embedded SQL engine to process unsupported operations client-side (often SQL functions and JOIN operations).
Connecting to Bitbucket Data
Connecting to Bitbucket data looks just like connecting to any relational data source. Create a connection string using the required connection properties. For this article, you will pass the connection string as a parameter to the create_engine function.
For most queries, you must set the Workspace. The only exception to this is the Workspaces table, which does not require this property to be set, as querying it provides a list of workspace slugs that can be used to set Workspace. To query this table, you must set Schema to 'Information' and execute the query SELECT * FROM Workspaces>.
Setting Schema to 'Information' displays general information. To connect to Bitbucket, set these parameters:
- Schema: To show general information about a workspace, such as its users, repositories, and projects, set this to Information. Otherwise, set this to the schema of the repository or project you are querying. To get a full set of available schemas, query the sys_schemas table.
- Workspace: Required if you are not querying the Workspaces table. This property is not required for querying the Workspaces table, as that query only returns a list of workspace slugs that can be used to set Workspace.
Authenticating to Bitbucket
Bitbucket supports OAuth authentication only. To enable this authentication from all OAuth flows, you must create a custom OAuth application, and set AuthScheme to OAuth.
Be sure to review the Help documentation for the required connection properties for you specific authentication needs (desktop applications, web applications, and headless machines).
Creating a custom OAuth application
From your Bitbucket account:
- Go to Settings (the gear icon) and select Workspace Settings.
- In the Apps and Features section, select OAuth Consumers.
- Click Add Consumer.
- Enter a name and description for your custom application.
- Set the callback URL:
- For desktop applications and headless machines, use http://localhost:33333 or another port number of your choice. The URI you set here becomes the CallbackURL property.
- For web applications, set the callback URL to a trusted redirect URL. This URL is the web location the user returns to with the token that verifies that your application has been granted access.
- If you plan to use client credentials to authenticate, you must select This is a private consumer. In the driver, you must set AuthScheme to client.
- Select which permissions to give your OAuth application. These determine what data you can read and write with it.
- To save the new custom application, click Save.
- After the application has been saved, you can select it to view its settings. The application's Key and Secret are displayed. Record these for future use. You will use the Key to set the OAuthClientId and the Secret to set the OAuthClientSecret.
Follow the procedure below to install SQLAlchemy and start accessing Bitbucket through Python objects.
Install Required Modules
Use the pip utility to install the SQLAlchemy toolkit and SQLAlchemy ORM package:
pip install sqlalchemy
pip install sqlalchemy.orm
Be sure to import the appropriate modules:
from sqlalchemy import create_engine, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Model Bitbucket Data in Python
You can now connect with a connection string. Use the create_engine function to create an Engine for working with Bitbucket data.
NOTE: Users should URL encode the any connection string properties that include special characters. For more information, refer to the SQL Alchemy documentation.
engine = create_engine("bitbucket:///?Workspace=myworkspaceslug&Schema=InformationInitiateOAuth=GETANDREFRESH&OAuthSettingsLocation=/PATH/TO/OAuthSettings.txt")
Declare a Mapping Class for Bitbucket Data
After establishing the connection, declare a mapping class for the table you wish to model in the ORM (in this article, we will model the Issues table). Use the sqlalchemy.ext.declarative.declarative_base function and create a new class with some or all of the fields (columns) defined.
base = declarative_base()
class Issues(base):
__tablename__ = "Issues"
Title = Column(String,primary_key=True)
ContentRaw = Column(String)
...
Query Bitbucket Data
With the mapping class prepared, you can use a session object to query the data source. After binding the Engine to the session, provide the mapping class to the session query method.
Using the query Method
engine = create_engine("bitbucket:///?Workspace=myworkspaceslug&Schema=InformationInitiateOAuth=GETANDREFRESH&OAuthSettingsLocation=/PATH/TO/OAuthSettings.txt")
factory = sessionmaker(bind=engine)
session = factory()
for instance in session.query(Issues).filter_by(Id="1"):
print("Title: ", instance.Title)
print("ContentRaw: ", instance.ContentRaw)
print("---------")
Alternatively, you can use the execute method with the appropriate table object. The code below works with an active session.
Using the execute Method
Issues_table = Issues.metadata.tables["Issues"]
for instance in session.execute(Issues_table.select().where(Issues_table.c.Id == "1")):
print("Title: ", instance.Title)
print("ContentRaw: ", instance.ContentRaw)
print("---------")
For examples of more complex querying, including JOINs, aggregations, limits, and more, refer to the Help documentation for the extension.
Insert Bitbucket Data
To insert Bitbucket data, define an instance of the mapped class and add it to the active session. Call the commit function on the session to push all added instances to Bitbucket.
new_rec = Issues(Title="placeholder", Id="1")
session.add(new_rec)
session.commit()
Update Bitbucket Data
To update Bitbucket data, fetch the desired record(s) with a filter query. Then, modify the values of the fields and call the commit function on the session to push the modified record to Bitbucket.
updated_rec = session.query(Issues).filter_by(SOME_ID_COLUMN="SOME_ID_VALUE").first()
updated_rec.Id = "1"
session.commit()
Delete Bitbucket Data
To delete Bitbucket data, fetch the desired record(s) with a filter query. Then delete the record with the active session and call the commit function on the session to perform the delete operation on the provided records (rows).
deleted_rec = session.query(Issues).filter_by(SOME_ID_COLUMN="SOME_ID_VALUE").first()
session.delete(deleted_rec)
session.commit()
Free Trial & More Information
Download a free, 30-day trial of the CData Python Connector for Bitbucket to start building Python apps and scripts with connectivity to Bitbucket data. Reach out to our Support Team if you have any questions.