def get_google_credentials(**kwargs): """ Returns Credentials that are able to authenticate against the Google APIs. Use the keyword arguments to provide further details (such as the scopes of the credentials). """ info = get_config('google').get('service account credentials') delegate = get_config('google').get('delegated admin') return service_account.Credentials.from_service_account_info( json.loads(info, strict=False), **kwargs).with_subject(delegate)
def init(self, *pargs, **kwargs): if get_config('stripe public key') is None or get_config( 'stripe secret key') is None: raise Exception( "In order to use a DAStripe object, you need to set stripe public key and stripe secret key in your Configuration." ) super().init(*pargs, **kwargs) if not hasattr(self, 'button_label'): self.button_label = "Zaplatit" if not hasattr(self, 'button_color'): self.button_color = "primary" if not hasattr(self, 'error_message'): self.error_message = "Zkuste prosím jiný způsob platby." self.is_setup = False
def geolocate(self): """Determines the latitude and longitude of the location.""" if self.geolocated: return self.geolocate_success the_address = self.address_for_geolocation() logmessage("Trying to geolocate " + str(the_address)) from pygeocoder import Geocoder google_config = get_config('google') if google_config and 'api key' in google_config: my_geocoder = Geocoder(api_key=google_config['api key']) else: my_geocoder = Geocoder() results = my_geocoder.geocode(the_address) self.geolocated = True if len(results): self.geolocate_success = True self.location.gathered = True self.location.known = True self.location.latitude = results[0].coordinates[0] self.location.longitude = results[0].coordinates[1] self.location.description = self.block() self.geolocate_response = results.raw geo_types = {'administrative_area_level_2': 'county', 'neighborhood': 'neighborhood', 'postal_code': 'zip', 'country': 'country'} for geo_type, addr_type in geo_types.iteritems(): if hasattr(results[0], geo_type) and not hasattr(self, addr_type): logmessage("Setting " + str(addr_type) + " to " + str(getattr(results[0], geo_type)) + " from " + str(geo_type)) setattr(self, addr_type, getattr(results[0], geo_type)) #else: #logmessage("Not setting " + addr_type + " from " + geo_type) #logmessage(json.dumps(self.geolocate_response)) else: logmessage("valid not ok: result count was " + str(len(results))) self.geolocate_success = False return self.geolocate_success
def get_server_config(self, auth_only=False): # auth_only allows you to grab only the client-id from the configuration for the # purpose of running authentication requests. docusign_configuration = get_config('docusign') if not docusign_configuration: raise DAError( "Attempt to read DocuSign configuration failed. DocuSign is not configured for the server." ) else: #Import the client_ID or throw an error. if 'client-id' in docusign_configuration: self.client_id = docusign_configuration['client-id'] else: raise DAError( "DocuSign configuration does not include client-id.") if 'test-mode' in docusign_configuration: self.test_mode = docusign_configuration['test-mode'] else: raise DAError( "DocuSign configuration does not include test-mode.") if not auth_only: # Get the rest of the required configuration variables here. if 'impersonated-user-guid' in docusign_configuration: self.impersonated_user_guid = docusign_configuration[ 'impersonated-user-guid'] else: raise DAError( "DocuSign confinguration does not include impersonated-user-guid." ) if 'private-key' in docusign_configuration: self.private_key = docusign_configuration['private-key'] else: raise DAError( "DocuSign configuration does not include private-key.")
def fetch_google_street_view_image(self): google_api_key = get_config('google', dict()).get('api key', None) if google_api_key is None: raise Exception("No Google Maps API key") street_view_image = tempfile.NamedTemporaryFile(prefix="datemp", suffix=".png") google_address = urllib.quote(self.one_line(with_city_state=True)) the_url = 'https://maps.googleapis.com/maps/api/streetview?size=640x640&location=' + google_address + '&key=' + google_api_key try: urllib.urlretrieve(the_url, street_view_image.name) except Exception as err: raise Exception('Error retrieving Google Street View image') street_view_pdf = DAFile() street_view_pdf.set_random_instance_name() street_view_pdf.initialize(filename="Google_Street_View.pdf") png_to_pdf(street_view_image.name, street_view_pdf.path()) street_view_pdf.retrieve() street_view_pdf.commit() street_view_png = DAFile() street_view_png.set_random_instance_name() street_view_png.initialize(filename="Google_Street_View.png") street_view_png.copy_into(street_view_image.name) street_view_png.retrieve() street_view_png.commit() self.google_street_view_pdf = street_view_pdf self.google_street_view_image = street_view_png
def ljo_account(): """ Returns the email address of the service account that is used for automation actions. """ info = get_config('google').get('service account credentials') data = json.loads(info, strict=False) return data["client_email"]
def short_url(): info = user_info() url = None for key, val in get_config('dispatch').iteritems(): interview_name = re.sub(r'\:([^\/]+)$', r':data/questions/\1', val) if interview_name == info.filename: url = '%sstart/%s?session=%s' % (url_of( 'root', _external=True), key, info.session) break if url is None: url = interview_url() return url
def get_pdf(self, indexno=None, fileno=None, pageno=None, filename=None): api_key = get_config('docket api key') if indexno is None or fileno is None or pageno is None or filename is None: raise Exception("get_pdf: invalid input") new_file = DAFile() new_file.set_random_instance_name() new_file.initialize(filename=filename) new_file.from_url("https://docket.philalegal.org/docketinfo?docketnum=" + str(self.docketnum) + '&indexno=' + str(indexno) + '&fileno=' + str(fileno) + '&pageno=' + str(pageno) + "&key=" + api_key) #new_file.make_pngs() new_file.retrieve() new_file.commit() return new_file
def result(self): if hasattr(self, '_active_result') and hasattr( self, '_active_source') and self._active_source == self.source: return self._active_result if hasattr(self, '_active_result'): del self._active_result if hasattr(self, '_full_result'): del self._full_result self._active_source = self.source api_key = get_config('spot api key') if api_key is None: raise Exception( "Cannot run Spot api without a 'spot api key' directive in the Configuration." ) input_data = { "text": self._active_source, "save-text": 0, "cutoff-lower": 0.25, "cutoff-pred": 0.5, "cutoff-upper": 0.5 } headers = { "Authorization": "Bearer " + api_key, "Content-Type": "application/json", "Accept": "application/json" } r = requests.post(api_root + '/entities-nested/', json=input_data, headers=headers) success = True if r.status_code != 200: success = False log('Spot API returned non-success status code ' + str(r.status_code) + "\n" + str(r.text)) if success: try: self._full_result = r.json() except: success = False log('Spot API did not return valid JSON') if success and ('labels' not in self._full_result or len(self._full_result['labels']) == 0): success = False log('Spot API returned no results') if success and 'name' not in self._full_result['labels'][-1]: success = False log('Spot API returned a result but it lacked a name') if success: self._active_result = self._full_result['labels'][-1]['name'] else: self._active_result = None return self._active_result
def fetch_docket(self): api_key = get_config('docket api key') http = httplib2.Http() try: resp, content = http.request("https://docket.philalegal.org/docketinfo?docketnum=" + str(self.docketnum) + "&key=" + str(api_key), "GET") if int(resp['status']) == 200: result = json.loads(content) else: result = dict(docketnum=self.docketnum, success=False, error="API call failed") except Exception as err: result = dict(docketnum=self.docketnum, success=False, error=str(err)) if not result.get('success', False): raise Exception(result.get('error', 'There was an error getting the docket')) self.docket_info = result self.docket_fetched = True
def _get_flow(self): app_credentials = get_config('oauth', dict()).get(self.appname, dict()) client_id = app_credentials.get('id', None) client_secret = app_credentials.get('secret', None) if client_id is None or client_secret is None: raise Exception('The application ' + self.appname + " is not configured in the Configuration") flow = oauth2client.client.OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=self.scope, redirect_uri=re.sub(r'\?.*', '', interview_url()), auth_uri=self.auth_uri, token_uri=self.token_uri, access_type='offline', prompt='consent') return flow
def translate_phrase(phrase, source_language, target_language): try: api_key = get_config('google')['api key'] except: log("Could not translate because Google API key was not in Configuration." ) return phrase try: service = build('translate', 'v2', developerKey=api_key) resp = service.translations().list(source=source_language, target=target_language, q=[phrase]).execute() return re.sub(r''', r"'", str(resp['translations'][0]['translatedText'])) except Exception as err: log("translation failed: " + err.__class__.__name__ + ": " + str(err)) return phrase
def geolocate(self): if self.geolocated: return self.geolocate_success the_address = self.address_for_geolocation() logmessage("Trying to geolocate " + str(the_address)) from pygeocoder import Geocoder google_config = get_config('google') if google_config and 'api key' in google_config: my_geocoder = Geocoder(api_key=google_config['api key']) else: my_geocoder = Geocoder() results = my_geocoder.geocode(the_address) self.geolocated = True if len(results): self.geolocate_success = True self.location.gathered = True self.location.known = True self.location.latitude = results[0].coordinates[0] self.location.longitude = results[0].coordinates[1] self.location.description = self.block() self.geolocate_response = results.raw geo_types = { 'administrative_area_level_2': 'county', 'neighborhood': 'neighborhood', 'postal_code': 'zip', 'country': 'country' } for geo_type, addr_type in geo_types.iteritems(): if hasattr(results[0], geo_type) and not hasattr(self, addr_type): logmessage("Setting " + str(addr_type) + " to " + str(getattr(results[0], geo_type)) + " from " + str(geo_type)) setattr(self, addr_type, getattr(results[0], geo_type)) #else: #logmessage("Not setting " + addr_type + " from " + geo_type) #logmessage(json.dumps(self.geolocate_response)) else: logmessage("valid not ok: result count was " + str(len(results))) self.geolocate_success = False return self.geolocate_success
import gspread import json from docassemble.base.util import get_config from oauth2client.service_account import ServiceAccountCredentials credential_json = get_config('google', dict()).get('service account credentials', None) if credential_json is None: credential_info = None else: credential_info = json.loads(credential_json, strict=False) scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] __all__ = ['read_sheet', 'append_to_sheet'] def read_sheet(sheet_name, worksheet_index=0): creds = ServiceAccountCredentials.from_json_keyfile_dict(credential_info, scope) client = gspread.authorize(creds) sheet = client.open(sheet_name).get_worksheet(worksheet_index) return sheet.get_all_records() def append_to_sheet(sheet_name, vals, worksheet_index=0): creds = ServiceAccountCredentials.from_json_keyfile_dict(credential_info, scope) client = gspread.authorize(creds) sheet = client.open(sheet_name).get_worksheet(worksheet_index) sheet.append_row(vals)
import requests import json import importlib from docassemble.base.util import log, get_config, interview_url # reference: https://gist.github.com/JeffPaine/3145490 # https://docs.github.com/en/free-pro-team@latest/rest/reference/issues#create-an-issue # Authentication for user filing issue (must have read/write access to # repository to add issue to) __all__ = ['valid_github_issue_config', 'make_github_issue', 'feedback_link'] USERNAME = get_config('github issues', {}).get('username') TOKEN = get_config('github issues', {}).get('token') def valid_github_issue_config(): return bool(TOKEN) def feedback_link(user_info_object=None, i: str = None, github_repo: str = None, github_user: str = None, variable: str = None, question_id: str = None, package_version=None, filename=None) -> str: """ Helper function to get a link to the GitHub feedback form. For simple usage, it should be enough to call `feedback_link(user_info(), github_user="******")`, so long as the package you
def feedback_link(user_info_object=None, i: str = None, github_repo: str = None, github_user: str = None, variable: str = None, question_id: str = None, package_version=None, filename=None) -> str: """ Helper function to get a link to the GitHub feedback form. For simple usage, it should be enough to call `feedback_link(user_info(), github_user="******")`, so long as the package you want to provide feedback on exists on GitHub and you are running from an "installed" (not playground) link. """ if user_info_object: package_name = str(user_info_object.package) # TODO: we can use the packages table or /api/packages to get the exact GitHub URL if package_name and not package_name.startswith( "docassemble-playground"): _github_repo = package_name.replace('.', '-') else: _github_repo = "demo" # default repo on GitHub of suffolklitlab-issues/demo for documentation purposes _variable = user_info_object.variable _question_id = user_info_object.question_id _filename = user_info_object.filename try: _package_version = str( importlib.import_module(user_info_object.package).__version__) except: _package_version = "playground" if get_config('github issues', {}).get('default repository owner'): _github_user = get_config('github issues', {}).get('default repository owner') # Allow keyword params to override any info from the user_info() object # We will try pulling the repo owner name from the Docassemble config if github_repo and github_user: _github_repo = github_repo _github_user = github_user elif get_config('github issues', {}).get('default repository owner') and github_repo: _github_user = get_config('github issues', {}).get('default repository owner') _github_repo = github_repo else: _github_repo = "demo" _github_user = "******" if variable: _variable = variable if question_id: _question_id = question_id if package_version: _package_version = package_version if filename: _filename = filename if not i: i = "docassemble.GithubFeedbackForm:feedback.yml" return interview_url(i=i, github_repo=_github_repo, github_user=_github_user, variable=_variable, question_id=_question_id, package_version=_package_version, filename=_filename, local=False, reset=1)
def javascript(self): if not self.is_setup: self.setup() billing_details = dict() try: billing_details['name'] = str(self.payor) except: pass address = dict() try: address['postal_code'] = self.payor.billing_address.zip except: pass try: address['line1'] = self.payor.billing_address.address address['line2'] = self.payor.billing_address.formatted_unit() address['city'] = self.payor.billing_address.city if hasattr(self.payor.billing_address, 'country'): address['country'] = address.billing_country else: address['country'] = 'US' except: pass if len(address): billing_details['address'] = address try: billing_details['email'] = self.payor.email except: pass try: billing_details['phone'] = self.payor.phone_number except: pass return """\ <script> var stripe = Stripe(""" + json.dumps(get_config('stripe public key')) + """); var elements = stripe.elements(); var style = { base: { color: "#32325d", } }; var card = elements.create("card", { style: style }); card.mount("#stripe-card-element"); card.addEventListener('change', ({error}) => { const displayError = document.getElementById('stripe-card-errors'); if (error) { displayError.textContent = error.message; } else { displayError.textContent = ''; } }); var submitButton = document.getElementById('stripe-submit'); submitButton.addEventListener('click', function(ev) { stripe.confirmCardPayment(""" + json.dumps( self.intent.client_secret) + """, { payment_method: { card: card, billing_details: """ + json.dumps(billing_details) + """ } }).then(function(result) { if (result.error) { flash(result.error.message + " " + """ + json.dumps( word(self.error_message)) + """, "danger"); } else { if (result.paymentIntent.status === 'succeeded') { action_perform(""" + json.dumps(self.instanceName + '.success') + """, {result: result})
from docassemble.base.util import get_config from docassemble.base.util import DAObject, DAList ## Assuming you've added your airtable creds into the Config YAML: at_api_key = get_config('AIRTABLE API KEY') at_base_lmm = get_config('AT BASE LMM') ## Need to install package airtable-python-wrapper for this ## import airtable from airtable import Airtable import requests matter_table = Airtable(at_base_lmm, 'Matters', api_key=at_api_key) intake_table = Airtable(at_base_lmm, 'Intake copy', api_key=at_api_key) documents_table = Airtable(at_base_lmm, 'Documents', api_key=at_api_key) tasks_table = Airtable(at_base_lmm, 'Tasks', api_key=at_api_key) document_type_table = Airtable(at_base_lmm, 'Document Types', api_key=at_api_key) client_table = Airtable(at_base_lmm, 'Clients', api_key=at_api_key) def get_matters(): show_this = [] for rec in matter_table.get_all(): matter_id = rec['id'] matter_short_name = rec['fields']['Client ... Issue'] show_this.append(tuple((matter_id, matter_short_name))) return show_this
import stripe import json from docassemble.base.util import word, get_config, action_argument, DAObject, prevent_going_back from docassemble.base.standardformatter import BUTTON_STYLE, BUTTON_CLASS stripe.api_key = get_config('stripe secret key') __all__ = ['DAStripe'] class DAStripe(DAObject): def init(self, *pargs, **kwargs): if get_config('stripe public key') is None or get_config( 'stripe secret key') is None: raise Exception( "In order to use a DAStripe object, you need to set stripe public key and stripe secret key in your Configuration." ) super().init(*pargs, **kwargs) if not hasattr(self, 'button_label'): self.button_label = "Zaplatit" if not hasattr(self, 'button_color'): self.button_color = "primary" if not hasattr(self, 'error_message'): self.error_message = "Zkuste prosím jiný způsob platby." self.is_setup = False def setup(self): float(self.amount) str(self.currency) self.intent = stripe.PaymentIntent.create( amount=int(float('%.2f' % self.amount) * 100.0),
def javascript(self): if not self.is_setup: self.setup() billing_details = dict() try: billing_details['name'] = str(self.payor) except: pass address = dict() try: address['postal_code'] = self.payor.billing_address.zip except: pass try: address['line1'] = self.payor.billing_address.address address['line2'] = self.payor.billing_address.formatted_unit() address['city'] = self.payor.billing_address.city if hasattr(self.payor.billing_address, 'country'): address['country'] = address.billing_country else: address['country'] = 'CZ' except: pass if len(address): billing_details['address'] = address try: billing_details['email'] = self.payor.email except: pass try: billing_details['phone'] = self.payor.phone_number except: pass return """\ <script> var stripe = Stripe(""" + json.dumps(get_config('stripe public key')) + """); var elements = stripe.elements(); var elementStyles = { base: { fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"', fontSize: '1rem', fontWeight: '400', lineHeight: '1.5', color: '#5a5a5a', backgroundColor: '#222', '::placeholder': { color: '#888', }, ':-webkit-autofill': { color: '#e39f48', }, }, invalid: { color: '#E25950', '::placeholder': { color: '#FFCCA5', }, }, }; var card = elements.create("card", { style: elementStyles }); card.mount("#stripe-card-element"); card.addEventListener('change', ({error}) => { const displayError = document.getElementById('stripe-card-errors'); if (error) { displayError.textContent = error.message; } else { displayError.textContent = ''; } }); var submitButton = document.getElementById('stripe-submit'); submitButton.addEventListener('click', function(ev) { stripe.confirmCardPayment(""" + json.dumps( self.intent.client_secret) + """, { payment_method: { card: card, billing_details: """ + json.dumps(billing_details) + """ } }).then(function(result) { if (result.error) { flash(result.error.message + " " + """ + json.dumps( word(self.error_message)) + """, "danger"); } else { if (result.paymentIntent.status === 'succeeded') { action_perform(""" + json.dumps(self.instanceName + '.success') + """, {result: result})
from apiclient.http import MediaFileUpload from datetime import datetime from docassemble.base.util import get_config from google.oauth2 import service_account from googleapiclient.discovery import build from gspread import authorize from json import loads from oauth2client import client from oauth2client.service_account import ServiceAccountCredentials scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] __all__ = ["new_entry"] credential_info = loads(get_config("google").get('service account credentials'), strict=False) def new_entry(sheet_name: str, folder_id: str, name: str, doc_name: str, doc_type: str, doc_id: str, document, worksheet_index=0): """ Adds a new upload entry to the Google Spreadsheet identified by sheet_name The entry has the following form: """ creds = ServiceAccountCredentials.from_json_keyfile_dict(credential_info, scope) client = authorize(creds) sheet = client.open(sheet_name).get_worksheet(worksheet_index) now = datetime.now().strftime("%m/%d/%Y %H:%M:%S") sheet.append_row([now, name, doc_name, doc_type, doc_id]) service = build('drive', 'v3', credentials=creds)
import gspread import json from docassemble.base.util import get_config from oauth2client.service_account import ServiceAccountCredentials credential_info = json.loads(get_config('google docs credentials'), strict=False) scope = ['https://spreadsheets.google.com/feeds'] __all__ = ['read_sheet', 'append_to_sheet'] def read_sheet(sheet_name, worksheet_index=0): creds = ServiceAccountCredentials.from_json_keyfile_dict( credential_info, scope) client = gspread.authorize(creds) sheet = client.open(sheet_name).get_worksheet(worksheet_index) return sheet.get_all_records() def append_to_sheet(sheet_name, vals, worksheet_index=0): creds = ServiceAccountCredentials.from_json_keyfile_dict( credential_info, scope) client = gspread.authorize(creds) sheet = client.open(sheet_name).get_worksheet(worksheet_index) sheet.append_row(vals)
import gspread import json from docassemble.base.util import get_config from oauth2client.service_account import ServiceAccountCredentials credential_info = json.loads( get_config('google').get('service account credentials'), strict=False) scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] __all__ = ['read_sheet', 'append_to_sheet'] def read_sheet(sheet_key, worksheet_index): creds = ServiceAccountCredentials.from_json_keyfile_dict( credential_info, scope) client = gspread.authorize(creds) sheet = client.open_by_key(sheet_key).get_worksheet(worksheet_index) return sheet.get_all_records() def append_to_sheet(sheet_key, vals, worksheet_index=0): creds = ServiceAccountCredentials.from_json_keyfile_dict( credential_info, scope) client = gspread.authorize(creds) sheet = client.open_by_key(sheet_key).get_worksheet(worksheet_index) sheet.append_row(vals)
import requests from docassemble.base.util import get_config import json ecomailKey = get_config('ecomailKey') def detailEcomail (email): header = {'key': ecomailKey,'Content-Type': 'application/json'} r = requests.get('https://api2.ecomailapp.cz/subscribers/'+email, headers=header) return r.json() def addEcomail (email, id, vzor): header = {'key': ecomailKey,'Content-Type': 'application/json'} contact = detailEcomail(email) if "tags" in contact: tagy = contact["subscriber"]["tags"] else: tagy = [] tagy.append("OBČAN 2.0") tagy.append("Vzor") values = {} values["subscriber_data"] = {} values["subscriber_data"]["email"] = email values["subscriber_data"]["tags"] = list(set(tagy)) values["trigger_autoresponders"] = True values["update_existing"] = True
from docassemble.base.util import CustomDataType, DAObject, get_config, log import requests __all__ = ['SpotResult'] api_root = get_config('spot api url', 'https://spot.suffolklitlab.org/v0') class SpotResult(DAObject): @property def id(self): if self.result is None: return None if 'id' not in self._full_result['labels'][-1]: log('Spot API returned a result but it lacked an id') return None return self._full_result['labels'][-1]['id'] @property def result(self): if hasattr(self, '_active_result') and hasattr( self, '_active_source') and self._active_source == self.source: return self._active_result if hasattr(self, '_active_result'): del self._active_result if hasattr(self, '_full_result'): del self._full_result self._active_source = self.source api_key = get_config('spot api key') if api_key is None: raise Exception(
import importlib import json import requests from typing import Optional from docassemble.base.util import log, get_config, interview_url # reference: https://gist.github.com/JeffPaine/3145490 # https://docs.github.com/en/free-pro-team@latest/rest/reference/issues#create-an-issue # Authentication for user filing issue (must have read/write access to # repository to add issue to) __all__ = ["valid_github_issue_config", "make_github_issue", "feedback_link"] USERNAME = get_config("github issues", {}).get("username") TOKEN = get_config("github issues", {}).get("token") def valid_github_issue_config(): return bool(TOKEN) def feedback_link( user_info_object=None, i: str = None, github_repo: str = None, github_user: str = None, variable: str = None, question_id: str = None, package_version: str = None, filename: str = None, ) -> str: """
def fetch_philadox_info(self): r = DARedis() while r.get('using_philadox') is not None: time.sleep(5) pipe = r.pipeline() pipe.set('using_philadox', 1) pipe.expire('using_philadox', 120) pipe.execute() tdir = tempfile.mkdtemp() info = urllib.quote(json.dumps([self.address['number'], self.address['direction'], self.address['street'], tdir, get_config('philadox username'), get_config('philadox password')])) step = ['casperjs', DAStaticFile(filename='eagleweb.js').path(), info] result = subprocess.call(step) r.delete('using_philadox') if result != 0: raise Exception("Failed to fetch Philadox information") outfiles = [] for pdf_file in sorted([f for f in os.listdir(tdir) if f.endswith('.pdf')]): new_file = DAFile() new_file.set_random_instance_name() new_file.initialize(filename=pdf_file) new_file.copy_into(os.path.join(tdir, pdf_file)) new_file.retrieve() new_file.commit() outfiles.append(new_file) self.philadox_files = outfiles
def hs_smlouva(idSmlouvy): header = {"Authorization": "Token "+get_config('HlidacStatuKey')} url = "https://www.hlidacstatu.cz/Api/v2/Smlouvy/"+idSmlouvy r = requests.get(url, headers=header) return r.json()
from datetime import datetime from docassemble.base.core import DAFile from docassemble.base.functions import defined, get_user_info, interview_url from docassemble.base.util import get_config, send_email, user_info from psycopg2 import connect from textwrap import dedent from typing import Optional, Tuple __all__ = [ "can_access_submission", "get_accessible_submissions", "get_files", "initialize_db", "new_entry", "send_attachments", "url_for_submission" ] db_config = get_config("filesdb") def initialize_db(): """ Initialize the postgres tables for courts and files. We expect to have an entry 'filesdb' in the main configuration yaml. Below is a sample config: filesdb: database: uploads user: uploads password: Password1! host: localhost port: 5432 This user should have access to the database (read, write) """
import logging import json from google.oauth2 import service_account import google.cloud.storage from docassemble.base.util import get_config from oauth2client.service_account import ServiceAccountCredentials logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) credential_json = get_config('google', {}).get('service account credentials', None) if credential_json is None: credential_info = None else: credential_info = json.loads(credential_json, strict=False) def google_api_credentials(scope): """Returns an OAuth2 credentials object for the given scope.""" if credential_info is None: raise Exception("google service account credentials not defined in configuration") if scope is None: scope = ['https://www.googleapis.com/auth/drive'] if type(scope) is not list: scope = [scope] return ServiceAccountCredentials.from_json_keyfile_dict(credential_info, scope) def google_cloud_credentials(scope): """Returns google.oauth2.service_account.Credentials that can be used with the google.cloud API.""" if credential_info is None: raise Exception("google service account credentials not defined in configuration") if scope is None: scope = ['https://www.googleapis.com/auth/devstorage.full_control']
from docassemble.base.core import DAObject, DAList from docassemble.base.util import get_config, Thing from docassemble.base.functions import word from .airtable import Airtable api_key = get_config('airtable api key') def object_from_a_id(a_id): funcobject = LegalObject() table_name = 'Elements' api_response = Airtable(base_key, table_name, api_key) el = api_response.get(a_id) if 'field' in el['fields']: funcobject.field = el['fields']['field'] if 'label' in el['fields']: funcobject.name = el['fields']['label'] funcobject.label = el['fields']['label'] if 'typeofhousing' in el['fields']: funcobject.typeofhousing = el['fields']['typeofhousing'] funcobject.id = el['id'] if 'datatype' in el['fields']: funcobject.datatype = el['fields']['datatype'] else: funcobject.datatype = 'yesno' if 'Active' in el['fields']: funcobject.active = el['fields']['Active'] else: funcobject.active = False if 'pleadingsection' in el['fields']: funcobject.pleadingsection = el['fields']['pleadingsection']