<commit_before>from os.path import exists
from os import environ
from string import Template

import plaid
from plaid.api import plaid_api
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.link_token_create_request import LinkTokenCreateRequest
from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
from plaid.model.products import Products
from plaid.model.country_code import CountryCode

from flask import Flask
from flask import request
from flask import send_file
from dotenv import load_dotenv

load_dotenv()

PORT=environ['PORT_NUMBER']

def env_lookup():
    env = environ['PLAID_ENV']
    if env == 'sandbox':
        return plaid.Environment.Sandbox
    if env == 'development':
        return plaid.Environment.Development
    if env == 'production':
        return plaid.Environment.Production
    raise Exception('Expected one of [sandbox|development|production] as an environment.')

def init_client():
    configuration = plaid.Configuration(
        host=env_lookup(),
        api_key={
            'clientId': environ['PLAID_CLIENT_ID'],
            'secret': environ['PLAID_SECRET']
        }
    )
    api_client = plaid.ApiClient(configuration)
    return plaid_api.PlaidApi(api_client)


client = init_client()
app = Flask(environ['APPLICATION_NAME'])


@app.route("/api/exchange-public-token", methods=['POST'])
def exchange_public_token():    
    exchange_request = ItemPublicTokenExchangeRequest(public_token=request.json['public_token'])
    exchange_response = client.item_public_token_exchange(exchange_request)
    access_token = exchange_response['access_token']
    with open(environ['ACCESS_TOKEN_STORAGE'], 'w') as f:
        f.write(access_token)
    return f"Access token written to: {environ['ACCESS_TOKEN_STORAGE']}"


@app.route("/api/create-link-token", methods=['GET'])
def create_link_token():
    req = LinkTokenCreateRequest(
            products=[Products("transactions")],
            client_name=environ['APPLICATION_NAME'],
            country_codes=[CountryCode('US')],
            language='en',
            user=LinkTokenCreateRequestUser(
                client_user_id='absent-user'
            ),
            redirect_uri=environ['PLAID_SANDBOX_REDIRECT_URI']
        )
    response = client.link_token_create(req)
    return response.to_dict()


@app.route("/", methods=['GET'])
def create_link():    
    template = 'home.html'
    if exists(environ['ACCESS_TOKEN_STORAGE']):
        template = 'exists.html'
        
    with open(template, "r") as file:
        data = file.read()

    t = Template(data)
    return t.safe_substitute(access_token_storage=environ['ACCESS_TOKEN_STORAGE'])


@app.route('/icon.svg')
def icon():
    return send_file('icon.svg', mimetype='image/svg+xml')


if __name__ == "__main__":
    app.run(port=PORT)<commit_msg>#20 update env var names<commit_after>from os.path import exists
from os import environ
from string import Template

import plaid
from plaid.api import plaid_api
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.link_token_create_request import LinkTokenCreateRequest
from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
from plaid.model.products import Products
from plaid.model.country_code import CountryCode

from flask import Flask
from flask import request
from flask import send_file
from dotenv import load_dotenv

load_dotenv()

PORT=environ['PORT_NUMBER']

def env_lookup():
    env = environ['PLAID_ENV']
    if env == 'sandbox':
        return plaid.Environment.Sandbox
    if env == 'development':
        return plaid.Environment.Development
    if env == 'production':
        return plaid.Environment.Production
    raise Exception('Expected one of [sandbox|development|production] as an environment.')

def init_client():
    configuration = plaid.Configuration(
        host=env_lookup(),
        api_key={
            'clientId': environ['PLAID_CLIENT_ID'],
            'secret': environ['PLAID_SECRET']
        }
    )
    api_client = plaid.ApiClient(configuration)
    return plaid_api.PlaidApi(api_client)


client = init_client()
app = Flask('Plaid2QIF Account Linker')


@app.route("/api/exchange-public-token", methods=['POST'])
def exchange_public_token():    
    exchange_request = ItemPublicTokenExchangeRequest(public_token=request.json['public_token'])
    exchange_response = client.item_public_token_exchange(exchange_request)
    access_token = exchange_response['access_token']
    with open(environ['ACCESS_TOKEN_FILE'], 'w') as f:
        f.write(access_token)
    return f"Access token written to: {environ['ACCESS_TOKEN_FILE']}"


@app.route("/api/create-link-token", methods=['GET'])
def create_link_token():
    req = LinkTokenCreateRequest(
            products=[Products("transactions")],
            client_name='Plaid2QIF Account Linker',
            country_codes=[CountryCode('US')],
            language='en',
            user=LinkTokenCreateRequestUser(
                client_user_id='absent-user'
            ),
            redirect_uri=environ['PLAID_SANDBOX_REDIRECT_URI']
        )
    response = client.link_token_create(req)
    return response.to_dict()


@app.route("/", methods=['GET'])
def create_link():    
    template = 'home.html'
    if exists(environ['ACCESS_TOKEN_FILE']):
        template = 'exists.html'
        
    with open(template, "r") as file:
        data = file.read()

    t = Template(data)
    return t.safe_substitute(access_token_storage=environ['ACCESS_TOKEN_FILE'])


@app.route('/icon.svg')
def icon():
    return send_file('icon.svg', mimetype='image/svg+xml')


if __name__ == "__main__":
    app.run(port=PORT)
{'fraction_non_alphanumeric': 0.10888004154405401, 'fraction_numerical': 0.0006924009001211701, 'mean_word_length': 3.9596566523605152, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5869755', 'n_tokens_mistral': 1751, 'n_tokens_neox': 1710, 'n_words': 349}