async def create_person(person_in: PersonCreate, deta: Deta = Depends(get_deta)): base = deta.Base('persons') person = person_in.dict() person['created_at'] = datetime.now().timestamp() person['updated_at'] = None person['deleted_at'] = None return base.put(person)
def get_anchor(anchor_id: str): deta = Deta() db = deta.Base("anchor") item = db.get(anchor_id) if (not item): return "not found", 404 return item["html"]
def get_subscribers(verified=True): deta = Deta(os.environ.get('DETA_PROJECT_KEY')) db = deta.Base("newsletter") subs_gen = db.fetch({'verified': verified}, pages=100, buffer=20) subs = [] for sub_gen in subs_gen: subs += sub_gen return subs
def query_subscriber(key): deta = Deta(os.environ.get('DETA_PROJECT_KEY')) db = deta.Base("newsletter") try: sub = next(db.fetch({'confirm_key': key}))[0] except IndexError: return None return sub
def remove_sub(key): deta = Deta(os.environ.get('DETA_PROJECT_KEY')) db = deta.Base("newsletter") try: sub = next(db.fetch({'confirm_key': key}))[0] except IndexError: return False email = sub.get('key') return db.delete(email) is None
def remove_all_unverified(): deta = Deta(os.environ.get('DETA_PROJECT_KEY')) db = deta.Base("newsletter") subs_gen = db.fetch({'verified': False}, pages=100, buffer=20) subs = [] for sub_gen in subs_gen: subs += sub_gen for sub in subs: db.delete(sub.get('key'))
def setUp(self): key = os.getenv("DETA_PROJECT_KEY") deta = Deta(key) self.db = deta.Base("test") self.item1 = {"key": "existing1", "value": "test"} self.item2 = {"key": "existing2", "value": 7} self.item3 = {"key": "existing3", "value": 44} self.item4 = {"key": "existing4", "value": {"name": "patrick"}} self.item5 = {"key": "%@#//#!#)#$_", "value": 0, "list": ["a"]} self.db.put_many([self.item1, self.item2, self.item3, self.item4, self.item5])
def update_stars(event=None, repos=repos): # Initialize with a Project Key deta = Deta() # This how to connect to or create a database. db = deta.Base("github_stars_db") for repo in repos: current_time = time.ctime() stars = get_github_stars(repo) db.put({"repo_name": repo, "time": current_time, "stars_count": stars}) print("FINISH PROCESS!") return f"Collect stats of repo {repos} and sent to DB!"
def setUp(self): key = os.getenv("DETA_SDK_TEST_PROJECT_KEY") name = os.getenv("DETA_SDK_TEST_BASE_NAME") self.assertIsNotNone(key) self.assertIsNotNone(name) deta = Deta(key) self.db = deta.Base(str(name)) self.item1 = {"key": "existing1", "value": "test"} self.item2 = {"key": "existing2", "value": 7} self.item3 = {"key": "existing3", "value": 44} self.item4 = {"key": "existing4", "value": {"name": "patrick"}} self.item5 = {"key": "%@#//#!#)#$_", "value": 0, "list": ["a"]} self.db.put_many( [self.item1, self.item2, self.item3, self.item4, self.item5])
async def reset_password_for_person(person_key: str, password_reset_in: PasswordResetIn, deta: Deta = Depends(get_deta), settings: Settings = Depends(get_settings)): password_reset_failed_exception = HTTPException(status.HTTP_401_UNAUTHORIZED, 'Password Reset Failed') payload = {} base = deta.Base('users') try: payload = jwt.decode(password_reset_in.token, settings.SECRET_KEY, 'HS256') except JWTError: raise password_reset_failed_exception key: str = payload.get('sub') if key is None: raise password_reset_failed_exception users = next(base.fetch({'key': key, 'can_login': True, 'deleted_at': None})) if not users: raise password_reset_failed_exception users[0]['password'] = get_crypt_context().hash(password_reset_in.password) return base.put(users[0])
import os from deta import Deta ## run this file one time deta = Deta('your_super_secret_deta_key') db = deta.Base('ot') def set_db(): payload = { "_type": "location", "acc": 1800, "alt": 78, "batt": 44, "bs": 1, "conn": "m", "created_at": 1612658146, "key": "viiobn6mj1pf", ##This string value can be modified but must be changed in the base.py and all the other fields to match "lat": 8.3690592, "lon": -62.6282535, "t": "u", "tid": "12", "tst": 1612657933, "vac": 1, "vel": 0 } set = db.insert(payload) print('Done')
# private_api -- this Micro is protected; an admin api for to dos from deta import Deta from fastapi import FastAPI from fastapi.responses import HTMLResponse from pydantic import BaseModel app = FastAPI() deta = Deta() todos = deta.Base("my_todos") # separate Base for each installed instance default_content = "Write code for Space" class ToDo(BaseModel): content: str = default_content done: bool = False is_public: bool = False @app.get("/") def html_handler(): return HTMLResponse(open("index.html").read()) @app.get("/todos") def list_todos(): all_todos = next(todos.fetch([])) return all_todos @app.get("/todos/{todo_key}") def display_todo(): return todos.get(todo_id)
def get_subscriber(email): deta = Deta(os.environ.get('DETA_PROJECT_KEY')) db = deta.Base("newsletter") return db.get(email)
def __init__(self, DB_Name): # authentication deta = Deta(os.environ['DETA_PROJECT_KEY']) self.db = deta.Base(DB_Name)
import json import os import random from deta import App, Deta from dotenv import load_dotenv from fastapi import FastAPI load_dotenv('env') app = App(FastAPI()) deta = Deta(os.environ.get('PROJECT_KEY')) db = deta.Base('quotes') db_appends = { 'posted_facebook_at': 'NULL', 'posted_telegram_at': 'NULL', 'posted_twitter_at': 'NULL', } def db_get_quotes(query): return list(db.fetch(query))[0] def db_cleanup_quotes(quotes): for quote in quotes: for k in db_appends.keys(): quote.pop(k, None) return quotes
#!/usr/bin/env python3 import os import jsonify as jsonify from deta import Deta from dotenv import load_dotenv from fastapi import FastAPI load_dotenv(verbose=True) app = FastAPI() deta = Deta(os.environ.get('DETA_PROJECT_KEY')) users = deta.Base('users') @app.get('/') def read_root(): users.insert({'name': 'Geordi', 'title': 'Chief Engineer'}) return 'Hello Deta!' @app.get('/users/{user_key}') def read_user(user_key: str): user = users.get(user_key) return user if user else jsonify({'error': 'Not found'}, 404)
import jinja2 from flask import Flask, redirect, Response from google.oauth2.credentials import Credentials from googleapiclient.discovery import build import base64 from google_auth_oauthlib.flow import InstalledAppFlow from jinja2 import Environment, select_autoescape import requests from deta import Deta env = Environment( loader=jinja2.FileSystemLoader('./'), autoescape=True ) deta = Deta() db = deta.Base('get-liked-music') google_data = {} with open("client_secrets.json", "r") as f: google_data = json.load(f)["web"] SCOPES = ['https://www.googleapis.com/auth/youtube'] refresh_token = os.getenv("REFRESH_TOKEN") """ flow = InstalledAppFlow.from_client_secrets_file("client_secrets.json", SCOPES) flow.redirect_uri = "http://localhost" authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline',
# -*- coding: utf-8 -*- # Simple Deta *detabase SDK* setup. from operator import itemgetter from deta import Deta from environs import Env env = Env() env.read_env() deta = Deta(env("PROJECT_KEY")) db = deta.Base("states") def get(state): """ Helper function specific state. """ if state: return next(db.fetch({"states?contains": state.capitalize()})) def get_all(): """ Return all states. """ return sorted(next(db.fetch()), key=itemgetter("abbr"))
from deta import Deta from .auth import DETA DB = Deta(DETA["project_key"]) ITEMS_DB = DB.Base("toys")
from fastapi import FastAPI, HTTPException from deta import Deta from auth import Auth from user_modal import AuthModal deta = Deta() users_db = deta.Base('users') app = FastAPI() auth_handler = Auth() @app.post('/signup') def signup(user_details: AuthModal): if users_db.get(user_details.username) != None: return 'Account already exists' try: hashed_password = auth_handler.encode_password(user_details.password) user = {'key': user_details.username, 'password': hashed_password} return users_db.put(user) except: error_msg = 'Failed to signup user' return error_msg @app.post('/login') def login(user_details: AuthModal): user = users_db.get(user_details.username) if (user is None): return HTTPException(status_code=401, detail='Invalid username') if (not auth_handler.verify_password(user_details.password, user['password'])):
def set_subscriber(email, key, verified=False): deta = Deta(os.environ.get('DETA_PROJECT_KEY')) db = deta.Base("newsletter") db.put({'verified': verified, 'confirm_key': key}, email)
from deta import Deta deta = Deta() folders_db = deta.Base("folders") feeds_db = deta.Base("feeds") def get_all(db, query): blob_gen = db.fetch(query) blobs = [] for stored_blob in blob_gen: for blob in stored_blob: blobs.append(blob) return blobs def create_folder(title): expanded = True folders = get_all(folders_db, {}) for folder in folders: if folder["title"] == title: return folder try: res = folders_db.put({"title": title, "is_expanded": expanded}) return res except: print("Something bad happened.") return None
"http://*****:*****@app.get("/") def read_root(): return {"This is simple API for SET game leaderboard"} @app.post("/records/") def create_record(record: Record):
from models import doctorModels, patientModel, consultationModel from deta import Deta import os deta = Deta(os.getenv('DETA_PROJECT_KEY')) dbDoctors = deta.Base('users') dbPatients = deta.Base('patients') dbConsultations = deta.Base('consultations') # ------ doctor actions async def add_doctor(doctor:doctorModels.Doctor): newDoctor = dbDoctors.put({ key: value for key, value in doctor }, key=doctor.email) return newDoctor async def update_doctor_token(email:str, token:str): dbDoctors.update({ 'token': token }, key=email) async def update_doctor_data(doctor:doctorModels.DoctorData): dbDoctors.update({ key: value for key, value in doctor if value }, key=doctor.email) async def update_doctor_password(email:str, newPassword:str): dbDoctors.update({
import requests from deta import App, Deta from fastapi import FastAPI from fastapi import FastAPI, Response from fastapi.responses import HTMLResponse from pydantic import BaseModel from jinja2 import Template fast = FastAPI() app = App(fast) deta = Deta() tweet_db = deta.Base("tweetbox") @app.get("/") def html_handler(): tweets = next(tweet_db.fetch([])) tweetHtml = {} for tweet in tweets: tweet_id = tweet.get("tweet_id") tweetHtml[tweet_id] = tweet.get("html") home_template = Template((open("index.html").read())) home_css = open("style.css").read() home_hyper = open("home.js").read() home_tweetcard = open("tweetcard.js").read() return HTMLResponse(home_template.render(home_js=home_hyper, tweets=tweetHtml, css=home_css, tweetcard=home_tweetcard))
from fastapi import FastAPI from pydantic import BaseModel from deta import Deta app = FastAPI() deta = Deta() db = deta.Base("people") class Person(BaseModel): name: str age: int @app.get("/") def hello(): return "Hello from Deta!" @app.post("/people") def save_person(person: Person): resp = db.put(person.dict()) return resp @app.get("/people") def people_list(): return db.fetch()
import os import base64 import bleach from pydantic import BaseModel from deta import Deta deta = Deta() notes = deta.Base("notes") base_url = "/" if not os.getenv("DETA_SPACE_APP"): base_url = "https://" + os.environ["DETA_PATH"] + ".deta.dev/" default_content = f"## Info:\n\nThis is a \"box\" of notes. \n\nEvery note has a url at: `{base_url}notes/:note_name`\n\nThe notes are also accessible via API:\n\n`GET {base_url}notes/:note_name?json=true`\n\nAnyone with **run access** can edit and view the note.\n\nYou can edit notes using the **edit** button, writing regular markdown.\n\nYou can [[link]] to any note in your box using the convention **[[~note_name]]**.\n- This creates bi-directional links. \n\nA list of all notes that link to the present note are under a header **Backlinks**.\n \n\n" def list_diff(list_one, list_two): diff_list = [x for x in list_one if x not in list_two] return diff_list class Note(BaseModel): name: str content: str = default_content links: list = [] backlinks: list = [] class Links(BaseModel):
from datetime import datetime import logging import os import re import requests from deta import App from deta import Deta from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware deta = Deta() app = App(FastAPI()) db = deta.Base("admetsar2") emaildb = deta.Base("emails") origins = ["http://*****:*****@zealseeker.com'
from typing import Optional from email_validator import EmailSyntaxError from pydantic.errors import EmailError from fastapi import FastAPI, Form, Header, Response, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from dotenv import load_dotenv from deta import Deta from pydantic import EmailStr, BaseModel from mailer import send_registration_mail, send_event_mails load_dotenv() deta = Deta(os.getenv("DETA_PROJECT_KEY")) db = deta.Base(os.getenv("DETA_DB_NAME")) subscriptions = deta.Base(os.getenv("DETA_SUBSCRIPTIONS_DB_NAME")) app = FastAPI() ALLOWED_ORIGINS = [ "https://troeptroep.nl", ] if os.getenv("DEBUG"): ALLOWED_ORIGINS.append("http://localhost:8000") app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_credentials=True, # no cookies
from deta import Deta KEY = 'project key' #Deta Key BASE = 'realtime' # detaBase name deta = Deta(KEY) # configure your Deta project db = deta.Base(BASE) # access your DB BaseKey = 'generated id' # paste the detabase key generated by db_config.py