class TestSuggestion(unittest.TestCase): def setUp(self): self.filename = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'data', 'test_db.tsv') self.db = Database() self.db.load(self.filename) self.suggestion = Suggestion(self.db) def test_get_name(self): response = self.suggestion.get('Abb') self.assertEqual(len(response['suggestions']), 1) self.assertEqual(response['suggestions'][0]['name'], 'Abbotsford, 02, CA') self.assertTrue(0 >= response['suggestions'][0]['score'] <= 1) def test_get_name_with_params(self): response = self.suggestion.get('Abb', -10, 10) self.assertEqual(len(response['suggestions']), 1) self.assertEqual(response['suggestions'][0]['name'], 'Abbotsford, 02, CA') self.assertTrue(0 >= response['suggestions'][0]['score'] <= 1)
def setUp(self): self.filename = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'data', 'test_db.tsv') self.db = Database() self.db.load(self.filename) self.suggestion = Suggestion(self.db)
def analyse(cls, team_info): repo_list = list() for item in team_info: repo_list += item["repos"] url_array = cls.process_url(repo_list) processed_array = list() for repo, code in zip(url_array, repo_list): try: processed_array.append( cls.crawl(repo, code, Config.opeg_commit)) except: print(sys.exc_info()[0], sys.exc_info()[1]) try: processed_array.append( cls.crawl(repo, code, Config.opeg_commit)) except: print(sys.exc_info()[0], sys.exc_info()[1]) # 두 번 실패했으므로 스킵함 continue print(json.dumps(processed_array, indent=4)) opeg_array = cls.evaluate(processed_array, team_info) # DB Transaction for team in opeg_array: Database.set_info(team) return opeg_array
def dbdo(): command_text = request.data.get('text') command_text = command_text.split(' ', 2) slack_uid = request.data.get('user_id') slackhelper = SlackHelper() actions = Actions(slackhelper, slack_uid) if command_text[0] not in allowed_commands: response_body = { 'text': 'Invalid Command Sent - `/dbdo help` for available commands' } if command_text[0] == 'help': response_body = actions.help() if command_text[0] in ['database', 'instance']: get_db = Database() get_db.__enter__() info_type = command_text[0] response_body = get_db.get_db_info(info_type) if command_text[0] == 'oug-city': set_city = Database() set_city.__enter__() name_in = command_text[1] city_in = command_text[2] response_body = set_city.oug_city(name_in, city_in) response = response_body return response
def __init__(self, application=None): self.application = application self.api = Api(self.application) self.database = Database() self.api.add_resource(EndPoint, '/suggestions', resource_class_kwargs={'db': self.database})
def pay_for_order (): data=request.form address=data['address'] address=address[0:200] address=address.strip() if address=="": return "Error, empty address" bitcoin=Bitcoin() database=Database() #address=re.sub('[^A-Za-z0-9:_-]','',address) address_salt=address+configuration.Configuration.salt address_salt=address_salt.encode() address_hash=hashlib.sha224(address_salt).hexdigest()[0:9] address=address.replace('\n', '|') address = re.sub('[^A-Za-z0-9:_-|]', '', address) item_index=data['index'] item_amount=data['amount'] item_index=re.sub('[^0-9]', '', item_index) item_amount=re.sub('[^0-9]', '', item_amount) item1=database.fetch_one_item(item_index) order_price=round(item1.price/bitcoin.btc_eur*float(item_amount),6) #print (order_price) order=Bitcoin.order(item_index,address,address_hash,item_amount,order_price) #print (order.order_index) return redirect("/pay/"+str(order.btc_address))
def add_item(): if 'adminkey' not in session: abort(404) elif (session['adminkey']!=hashlib.sha224(configuration.Configuration.secret_key.encode('utf-8')).hexdigest()): abort(404) database=Database() database.add_item() return redirect('/c')
def present_payment(btc_address): btc_address=re.sub('[^A-Za-z0-9]','',btc_address) bitcoin=Bitcoin() database=Database() order=database.fetch_one_order(btc_address) if order is None: return 'Error' else: return render_template('pay.html',order=order,rate=bitcoin.btc_eur,header=configuration.Configuration.header)
def show_item(index): index=re.sub('[^0-9]', '', index) database=Database() bitcoin=Bitcoin() item1=database.fetch_one_item(index) if item1 is None: abort(404) else: return render_template('item.html',index=index,item=item1,rate=bitcoin.btc_eur,header=configuration.Configuration.header)
def server(monkeypatch): # Copy over the test keys to the temporary key file keyf = tempfile.NamedTemporaryFile() with open('tests/app/data/keys.yml', mode='rb') as testkeyf: keyf.write(testkeyf.read()) keyf.flush() labelsf = tempfile.NamedTemporaryFile() with open('tests/app/data/labels.yml', mode='rb') as testlabelsf: labelsf.write(testlabelsf.read()) labelsf.flush() dbf = tempfile.NamedTemporaryFile() from app import routes # Stub key ring and database monkeypatch.setattr(routes, 'kr', KeyRing(keyf.name)) monkeypatch.setattr(routes, 'db', Database(dbf.name)) monkeypatch.setattr(routes, 'lm', LabelManager(labelsf.name)) import server server.app.config['TESTING'] = True proc = multiprocessing.Process( target=lambda: server.app.run(port=8800, debug=True)) proc.start() time.sleep(5) yield proc.terminate() keyf.close() labelsf.close() dbf.close()
def order_item(index,amount): index=re.sub('[^0-9]', '', index) amount=re.sub('[^0-9]', '', amount) database=Database() bitcoin=Bitcoin() item1=database.fetch_one_item(index) #print(item1.pcs) if item1 is None: return 'Error' else: from flask_wtf import FlaskForm from wtforms import TextAreaField,validators class OrderForm(FlaskForm): address=TextAreaField('Address', [validators.Length(min=10, max=200)]) order_form=OrderForm() return render_template('order.html',item=item1, index=index,rate=bitcoin.btc_eur, amount=int(amount),form=order_form,header=configuration.Configuration.header)
def admin_item(): if 'adminkey' not in session: abort(404) elif (session['adminkey']!=hashlib.sha224(configuration.Configuration.secret_key.encode('utf-8')).hexdigest()): abort(404) data = request.form item_name=data['name'] item_price=data['price'] item_avail=data['avail'] item_description=data['description'] item_index=data['index'] item_pcs=data['pcs'] database=Database() database.update_item(item_index,item_price,item_name,item_avail,item_description,item_pcs) return redirect('/c')
def delete(self, id): """ Menghapus soal """ sql = """delete from soal where id = %s""" params = [id] return Database().commit_data(sql, params)
def client(monkeypatch): # Copy over the test keys to the temporary key file keyf = tempfile.NamedTemporaryFile() with open('tests/app/data/keys.yml', mode='rb') as testkeyf: keyf.write(testkeyf.read()) keyf.flush() labelsf = tempfile.NamedTemporaryFile() with open('tests/app/data/labels.yml', mode='rb') as testlabelsf: labelsf.write(testlabelsf.read()) labelsf.flush() dbf = tempfile.NamedTemporaryFile() from app import routes, create_app # Stub key ring and database monkeypatch.setattr(routes, 'kr', KeyRing(keyf.name)) monkeypatch.setattr(routes, 'db', Database(dbf.name)) monkeypatch.setattr(routes, 'lm', LabelManager(labelsf.name)) import server server.app.config['TESTING'] = True yield server.app.test_client() keyf.close() labelsf.close() dbf.close()
def create_app(): app = FastAPI() settings = get_settings() db = Database() @app.middleware("http") async def db_session_middleware(request: Request, call_next): request.state.pool = db.pool response = await call_next(request) return response @app.on_event("startup") def startup(): database_instance.create_pool(settings) redis_instance.connect(settings) @app.on_event("shutdown") async def shutdown(): database_instance.close_pool() redis_instance.connect(settings) app.include_router(alumnos.router) app.include_router(temas.router) app.include_router(personas.router) app.include_router(cache_example.router) return app
async def wallets_list() -> List[WalletBase] == []: engine, session = Database().connect_to_db() wallets = session.query(WalletModel).all() session.close() return wallets
def detail(name): """팀당 소속 Repo, 팀원을 편집하거나 즉시 크롤링을 실행시킬 수 있는 관리 페이지.""" team = Database.get_info(name) if len(team) == 0: return redirect("/") #team_update = datetime.strptime(team["timestamp"], '%Y-%m-%dT%H:%M:%S %Z%z') team_update = parse(team["timestamp"]) team["g_timestamp"] = team_update.strftime("%Y년 %m월 %d일 %H시 %M분 %S초") for repo in team["repos"]: repo["g_license"] = "없음" \ if repo["license"] == "Unavailable" \ else repo["license"] language = str() for lang in repo["languages"]: language += lang["name"] + " (" + lang["percent"] + "%), " repo["g_languages"] = language[:-2] repo["g_issues"] = int(repo["issue_open"]) + int(repo["issue_closed"]) repo["g_pr"] = int(repo["pr_open"]) + int(repo["pr_closed"]) branches = str() for branch in repo["alive_branches"]: branches += branch + ", " repo["g_alive_branches"] = branches[:-2] contributors = str() for person in repo["contributors"]: contributors += person["name"] + " (" + str(person["count"]) + "개), " repo["g_contributors"] = contributors[:-2] issuers = str() for issuer in repo["issuers"].keys(): issuers += issuer + " (" + str(repo["issuers"][issuer]) + "개), " repo["g_issuers"] = issuers[:-2] return render_template('detail.html', description=Config.service_provider, team=team, team_list=Database.get_all(), cph_criteria=Config.opeg_commit)
class TestDatabase(unittest.TestCase): def setUp(self): self.db = Database() self.filename = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'data', 'test_db.tsv') def test_load(self): self.db.load(self.filename) self.assertEqual(len(self.db.cities), 3) self.assertEqual(self.db.cities[0].name, 'Abbotsford, 02, CA') def test_get(self): self.db.load(self.filename) result = self.db.get('Abb') self.assertEqual(len(result), 1) self.assertEqual(result[0].name, 'Abbotsford, 02, CA')
class RestServer: """ The RestServer class is in charge of the database and registers every resource ( endpoint ) """ def __init__(self, application=None): self.application = application self.api = Api(self.application) self.database = Database() self.api.add_resource(EndPoint, '/suggestions', resource_class_kwargs={'db': self.database}) def load_db(self, name): """ Loading the db from filename :param name: database file name :return: none """ self.database.load(name)
def put(self, id): """ Memperbaharui soal """ data = request.get_json() sql = """update soal set judul = %s, kunci_jawaban = %s, deskripsi = %s where id = %s""" params = [ data["judul"], pbh.hash(data["kunci_jawaban"]), data["deskripsi"], id ] return Database().commit_data(sql, params)
def post(self): """ Menambahkan soal """ data = request.get_json() sql = """insert into soal values(0,%s,%s,%s)""" params = [ data["judul"], pbh.hash(data["kunci_jawaban"]), data["deskripsi"] ] return Database().commit_data(sql, params)
def post(self): """ Memeriksa jawaban return True jika jawaban benar dan return False jika jawaban salah """ data = request.get_json() sql = """select * from soal where idsoal = %s""" hasil = Database().get_one(sql, [data["idsoal"]]) if pbh.verify(data["jawaban"], hasil["kunci_jawaban"]): return {"msg": "selamat jawaban anda benar"} else: return {"msg": "maaf jawaban anda salah"}
def console(): if 'adminkey' not in session: return redirect('/login') elif (session['adminkey']!=hashlib.sha224(configuration.Configuration.secret_key.encode('utf-8')).hexdigest()): return redirect('/login') database=Database() orders=database.get_orders(0) orders_interest=[] for order in orders: if (order.paid>0) or (order.note is not None): item=database.fetch_one_item(order.item_index) order.item_name=item.name orders_interest.append(order) orders=orders_interest items=database.get_items() required_items=[] for item in items: item.pcs=",".join(str(x) for x in item.pcs) required_items.append(item) items=required_items return render_template('admin.html',orders=orders,items=items,header=configuration.Configuration.header)
async def make_transaction(sender: int, recipient: int, amount: float) -> dict: commission = 0.015 engine, session = Database().connect_to_db() sender_ = session.query(WalletModel).filter_by(id=sender).first() recipient_ = session.query(WalletModel).filter_by(id=recipient).first() if not sender_: return {'error': 'Sender wallet does not exists'} if not recipient_: return {'error': 'Recipient wallet does not exists'} if sender == recipient: return {'error': 'Choose different recepient or sender'} if amount > sender_.balance: return {'error': 'Insufficient funds'} transaction_request = TransactionRequestModel(sender=sender_, recipient=recipient_, amount=amount) session.add(transaction_request) amount_after_commission = amount * (1 - commission) sender_.balance -= amount_after_commission recipient_.balance += amount session.commit() session.refresh(sender_) session.refresh(recipient_) session.close() return { "success": f"{amount} has been successfuly transfered to wallet {recipient_.id}" }
def admin_order(): if 'adminkey' not in session: abort(404) elif (session['adminkey']!=hashlib.sha224(configuration.Configuration.secret_key.encode('utf-8')).hexdigest()): abort(404) data = request.form database=Database() if 'note' not in data: database.delete_note(data['order_index']) else: database.create_note(data['order_index'],data['note']) return redirect('/c')
import config from app.db import Database from app.cams import cameras from app.keys import KeyRing from app.geo import search_places from flask_caching import Cache from flask import Flask, abort, request, render_template, jsonify from flask_sse import sse from datetime import datetime, timezone app = Flask(__name__) app.config.from_object(config) app.register_blueprint(sse, url_prefix='/location-stream') kr = KeyRing(config.KEYS_FILE) db = Database(config.DB_PATH) cache = Cache(app) def get_conf(loc): try: return config.LOCATIONS[loc] except KeyError: abort(404) @app.route('/') def index(): return render_template('index.html', locations=config.LOCATIONS.keys())
#!flask/bin/python from flask import Flask from flask import jsonify from flask import abort from flask import make_response from flask import request from flask import render_template from app.db import Database import json app = Flask(__name__) db = Database() @app.route('/', methods=['GET']) def hello(): return render_template('index.html') @app.errorhandler(404) def page_not_found(e): db.log(request) out = "<h1>404</h1>" return out # # Geral # @app.route('/geral/<int:zona_id>', methods=['GET']) def get_zona_one(zona_id):
from flask import Flask from flask_restful import Api from flask_cors import CORS from app.db import Database from flask_jwt_extended import JWTManager from app.config import Config app = Flask(__name__) app.config.from_object(Config) api = Api(app) db = Database(app) jwt = JWTManager(app) cors = CORS(app, resources={r"*": {"origins": "*"}}) @jwt.token_in_blacklist_loader def check_token(decrypted_token): jti = decrypted_token['jti'] sql = """select * from black_list_token where jti = %s""" res = db.get_one(sql, [jti]) return bool(res) from app.router import router
from app.db import Database from app.cache import Redis database_instance = Database() redis_instance = Redis()
""" This module holds everything related to the twitterbot """ from dotenv import load_dotenv, find_dotenv import requests, json, os from typing import List, Dict from app.db import Database import app.twitter as twitter from app.twitter import create_api load_dotenv(find_dotenv()) DB = Database() MAP_API = os.getenv("MAP_API") # Maps to Google Places API bot_name = os.getenv("BOT_NAME") # Need bot name """ bot_id is the twitter id for the Blue Witness Account. welcome_message_id is id of previously created welcome message using create_welcome_message in tweep.dm. dm_link is a link created from bot_id and welcome_message based on twitter api convention. dm_link link is tweeted to original incident tweet to invite them to dm us so we can start a conversation. """ bot_id = 1436057566807674897 welcome_message_id = 1440023048313131014 dm_link = f'https://twitter.com/messages/compose?recipient_id={bot_id}&welcome_message_id={welcome_message_id}' # These are the conversation statements the bot executes based on the max step of the conversation conversation_tree = { 1: "Hey, I'm working on the behalf of Blue Witness, can you give me more information regarding the incident you tweeted?", 10: "Click link below to start conversation.",