Last active
September 13, 2021 07:11
-
-
Save rome2o/794e297f1b9e11b70e7728682d6a7257 to your computer and use it in GitHub Desktop.
Teachable - Flask (Python) - Import Multiple Users through API - Looping API request in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Hi there, | |
| # Posting this for someone who will need this in future to import some users through API as it is otherwise required to subscribe to a higher package. | |
| # The following is a simple Flask application that would assume you've database with the right values, primary key and auto-increment on IDs. | |
| # A great idea is to sit inside Flask shell and do it. Thumbs up if it was helpful for you! | |
| # -*- coding: utf-8 -*- | |
| import os | |
| from flask import Flask, request | |
| from orator.orm import belongs_to, has_many, belongs_to_many | |
| from flask_orator import Orator, jsonify | |
| from collections import Counter | |
| import json | |
| import time | |
| import requests | |
| from requests.auth import HTTPBasicAuth | |
| # Configuration | |
| DEBUG = True | |
| ORATOR_DATABASES = { | |
| 'default': 'mysql', | |
| 'mysql': { | |
| 'driver': 'mysql', | |
| 'host': 'localhost', | |
| 'database': 'dbname', | |
| 'user': 'root', | |
| 'password': '', | |
| 'prefix': '' | |
| } | |
| } | |
| # Creating Flask application | |
| app = Flask(__name__) | |
| app.config.from_object(__name__) | |
| # Initializing Orator | |
| db = Orator(app) | |
| class User(db.Model): | |
| __fillable__ = ['name', 'email'] | |
| def syncUsers(): | |
| items = User.all() | |
| url = 'https://your-domain.teachable.com/api/v1/sales' | |
| for i in items: | |
| try: | |
| payload = {"name":i.first_name,"email":i.email,"price":0,"product_id":1234} | |
| response = requests.post(url, json=payload, auth = HTTPBasicAuth('user', 'pass')) | |
| response = json.loads(response.content) | |
| if response['is_active'] == False: | |
| raise Exception('Something has failed') | |
| print(response['is_active']) | |
| print(response['user']['meta']['name']) | |
| i.user_id = response['user_id'] | |
| i.save() | |
| time.sleep(0.5) | |
| except Exception: | |
| print(Exception) | |
| if __name__ == '__main__': | |
| app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment