Skip to content

Instantly share code, notes, and snippets.

@fjaguero

fjaguero/create_project.py Secret

Last active Nov 4, 2020
Embed
What would you like to do?
Lang.ai Multipart Python Example
import json
import requests
from urllib3.filepost import encode_multipart_formdata, choose_boundary
from urllib3.fields import RequestField
def encode_multipart_related(fields, boundary=None):
if boundary is None:
boundary = choose_boundary()
body, _ = encode_multipart_formdata(fields, boundary)
content_type = str('multipart/related; boundary=%s' % boundary)
return body, content_type
def encode_media_related(metadata, media, media_content_type):
# Field 1: Metadata
rf1 = RequestField(
name='metadata',
data=json.dumps(metadata),
headers={'Content-Type': 'application/json; charset=UTF-8'},
)
# Field 2: Media
rf2 = RequestField(
name='media',
data=media,
headers={'Content-Type': media_content_type},
)
return encode_multipart_related([rf1, rf2])
# Set the project metadata
metadata = {
'name': 'My test project',
'csvOptions': {
'textColumn': 'my_csv_text_column',
'dateColumn': 'my_csv_date_column'
},
'team_ids': ["team_id_one", "team_id_two"]
}
# Initialize media before reading the file
media = ''
# Read the file we want to upload and set as media
with open('dataset.csv') as f:
media = f.read()
# Set the body and headers for the request
# Get the API token from the Admin section
token = 'YOUR_API_TOKEN'
media_content_type = 'text/csv'
body, content_type = encode_media_related(metadata, media, media_content_type)
headers = {
'Content-Type': content_type,
'Authorization': str('Bearer %s' % token),
}
endpoint = "https://mycompany.lang.ai/api/v1/project"
r = requests.post(endpoint, data=body, headers=headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.