def setUp(cls): """Do once before all tests in this class""" # Get the Flask test client cls.client = app.test_client() # Show Flask errors that happen during tests app.config['TESTING'] = True # Connect to test database connect_to_db(app, "postgresql:///testdb") # Create tables from model db.create_all() # Import different types of data from seed file seed.load_users() seed.load_groups() seed.load_usergroups() seed.load_patterns() seed.load_invites() seed.set_val_user_id() seed.set_val_group_id() seed.set_val_usergroup_id() seed.set_val_pattern_id() seed.set_val_invite_id() with cls.client as c: with c.session_transaction() as sess: sess['user_id'] = 1 c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
def setUp(self): print "(setUp ran)" self.client = server.app.test_client() # Sets up fake test browser server.app.config['TESTING'] = True # Makes a 500 error in a route raise an error in a test connect_to_db(app, "postgresql:///testdb") # Connect to temporary DB db.create_all()
def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() app.config['TESTING'] = True # Connect to test database (uncomment when testing database) connect_to_db(app, "postgresql:///testdb") # Create tables and add sample data (uncomment when testing database) db.create_all() example_data() with self.client as c: with c.session_transaction() as sess: sess['RSVP'] = True def tearDown(self): """Do at end of every test.""" # (uncomment when testing database) db.session.close() db.drop_all() def test_games(self): result = self.client.get("/games") self.assertIn("Clue", result.data)
def message(): db.create_all() if request.values.get('Body', None).strip().lower() == 'register': user = Users.query.filter_by(number=request.values.get('From')).first() if user: user.active = 1 db.session.commit() else: user = Users(request.values.get('From')) db.session.add(user) db.session.commit() resp = twilio.twiml.Response() resp.message("Confirmed! Stay tuned for dog and cat pics! Text \"pause\" to stop hearing from us :( .") return str(resp) elif request.values.get('Body', None).strip().lower() == 'pause': user = Users.query.filter_by(number=request.values.get('From')).first() if not user: resp = twilio.twiml.Response() resp.message("Hmm - you're not in our system! Want to sign up? Reply with \"register\"") return str(resp) else: user.active = 0 db.session.commit() resp = twilio.twiml.Response() resp.message("You won't get any more messages - for now. Reply with \"register\" to start receiving again.") return str(resp) else: resp = twilio.twiml.Response() resp.message("Sorry - I don't understand that command!") return str(resp)
def setUp(self): """Do before every test.""" # Get the Flask test client self.client = app.test_client() # Show Flask errors that happen during tests app.config['TESTING'] = True # Connect to test database connect_to_db(app, "postgresql:///testdb") db.create_all() # Make mocks def _mock_get_yelp_search_results(term, location, category_filter, limit): """Mocks search results of Yelp API call for one restaurant.""" search_results = {"businesses": [{"rating": 4.5, "rating_img_url": "https://s3-media2.fl.yelpcdn.com/assets/2/www/img/99493c12711e/ico/stars/v1/stars_4_half.png", "review_count": 547, "name": "Saru Sushi Bar", "rating_img_url_small": "https://s3-media2.fl.yelpcdn.com/assets/2/www/img/a5221e66bc70/ico/stars/v1/stars_small_4_half.png", "url": "http://www.yelp.com/biz/saru-sushi-bar-san-francisco?utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=6XuCRI2pZ5pIvcWc9SI3Yg", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/5-ugy01zjSvudVsfdhmCsA/ms.jpg", "display_phone": "+1-415-400-4510", "id": "saru-sushi-bar-san-francisco", "location": {"city": "San Francisco", "postal_code": "94114", "country_code": "US", "address": ["3856 24th St"], "coordinate": {"latitude": 37.751706, "longitude": -122.4288283}, "state_code": "CA"}}]} return search_results def _mock_is_open_now_true(keyword, location): """Mocks Google Places API call to return True for current open status.""" return True self._old_is_open_now = process_results.is_open_now process_results.is_open_now = _mock_is_open_now_true self.old_get_yelp_search_results = server.yelp.search_query server.yelp.search_query = _mock_get_yelp_search_results
def init(configfile): app.config.from_pyfile('openmoves.cfg.default', silent=False) if configfile: if not os.path.exists(configfile): with open(configfile, 'w') as f: initialize_config(f) print("created %s" % configfile) app.config.from_pyfile(configfile, silent=False) assert app.config['SECRET_KEY'] SESSION_VERSION = 1 app.config['SECRET_KEY'] = "%s-%d" % (app.config['SECRET_KEY'], SESSION_VERSION) assert 'SQLALCHEMY_TRACK_MODIFICATIONS' not in app.config app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) with app.app_context(): if db.engine.name == 'sqlite': db.create_all() Bootstrap(app) app_bcrypt.init_app(app) login_manager.init_app(app) login_manager.login_view = "login" return app
def setUp(self): """Stuff to do before every test.""" # Get the Flask test client self.client = app.test_client() # Mock session # Connect to temporary database connect_to_db(app, "sqlite:///") # Create tables and add sample data db.create_all() sample_data() def _mock_grab_image_dimensions(filename): return (920, 764) self._old_grab_image_dimensions = server.grab_image_dimensions server.grab_image_dimensions = _mock_grab_image_dimensions def _mock_generate_thumb(filename, crop_thumb): return None self._old_generate_thumb = server.generate_thumb server.generate_thumb = _mock_generate_thumb
def setUp(self): print "(setUp ran)" self.client = server.app.test_client() server.app.config['TESTING'] = True connect_to_test_db(server.app) db.create_all()
def setUp(self): # Get the Flask test client self.client = app.test_client() # Show Flask errors that happen during tests app.config['TESTING'] = True # Connect to test database connect_to_db(app, "postgresql:///testdb") # Create tables from model db.create_all() # Import different types of data from seed file seed.load_users() seed.load_groups() seed.load_usergroups() seed.load_patterns() seed.load_invites() # Reset auto incrementing primary keys to start after seed data seed.set_val_user_id() seed.set_val_group_id() seed.set_val_usergroup_id() seed.set_val_pattern_id() seed.set_val_invite_id()
def setUp(self): """Do at the beginning of every test""" # Get the Flask test client self.client = app.test_client() # Show Flask errors that happen during tests app.config['TESTING'] = True # Connect to test database connect_to_db(app, "postgresql:///testdb") # Create tables from model db.create_all() # Import different types of data from seed file seed.load_users() seed.load_groups() seed.load_usergroups() seed.load_patterns() seed.load_invites() # Reset auto incrementing primary keys to start after seed data seed.set_val_user_id() seed.set_val_group_id() seed.set_val_usergroup_id() seed.set_val_pattern_id() seed.set_val_invite_id() with self.client as c: with c.session_transaction() as sess: sess['user_id'] = 1 c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get("FLASK_SECRET_KEY", "abcdef") db.init_app(app) with app.test_request_context(): db.create_all() return app
def setUp(self): # init tables db.create_all() # do imports from model import User from model import ItemCategory, ItemManufacturer, Item from model import LocationBuilding, Location from model import AssetInfo, Asset from model import Inventory # create objects u1 = User('bob') cat = ItemCategory('Computer') man = ItemManufacturer('Dell') item = Item(cat,man,'Optiplex 360') building = LocationBuilding('CEER') location = Location(building,'008') tag = AssetInfo('ee02547','13349') asset = Asset(tag,0,item,owner=u1,current=location,ip='153.104.47.23') import datetime inv = Inventory(u1,asset,datetime.datetime.now(),location) # add to database db.session.add(u1) db.session.add(cat) db.session.add(man) db.session.add(building) db.session.add(tag) db.session.add(item) db.session.add(location) db.session.add(asset) db.session.add(inv) db.session.commit()
def setUp(self): """Setup to do before every test.""" # Get the Flask test client self.client = app.test_client() # secret key to allow sessions to be used app.config['SECRET_KEY'] = 'sekrit!' # Show Flask errors that happen during tests app.config['TESTING'] = True # Connect to test database connect_to_db(app, db_uri="postgresql:///testdb") # Create tables and add sample data db.create_all() # create db records for yarns, users, baskets, basket_yarns, # projects, and patterns create_example_data() # create db records for preferences and user_preferences load_preferences("test_data/preference_data.txt") load_user_preferences("test_data/user_preference_data.txt") with self.client as c: with c.session_transaction() as session: session['username'] = '******'
def setUp(self): """Setup to do before every test.""" # Get the Flask test client self.client = app.test_client() app.jinja_env.undefined = StrictUndefined app.jinja_env.filters['prettify_preference'] = prettify_preference # Show Flask errors that happen during tests app.config['TESTING'] = True # Connect to test database connect_to_db(app, db_uri="postgresql:///testdb") # start with empty db db.drop_all() # Create tables and add sample data db.create_all() # create db records for yarns, users, baskets, basket_yarns, # projects, and patterns create_example_data() # create db records for preferences and user_preferences load_preferences("test_data/preference_data.txt") load_user_preferences("test_data/user_preference_data.txt") load_group_events("test_data/group-events.csv")
def __init__(self): logger.info("Message Manager init...") try: Message.query.all() except: db.create_all() logger.info("Message Manager init done...")
def setUp(self): print "\n\n\n\n (2) DOING A SEARCH TEST \n\n\n\n" self.client = app.test_client() app.config['TESTING'] = True postgrespassword = os.environ['POSTGRES_PASSWORD'] db_uri = 'postgresql://' + postgrespassword + '/test' connect_to_db(app, db_uri) db.create_all() load_regions() load_users() load_bestuses() load_categories() load_brands() load_products() load_tents() load_filltypes() load_gendertypes() load_sleepingbags() load_padtypes() load_sleepingpads() load_ratings() load_histories() load_test_postalcodes()
def setUp(self): self.client = app.test_client() app.config["TESTING"] = True app.config["SECRET_KEY"] = "key" connect_to_db(app, db_uri="postgresql:///testdb") db.create_all()
def setUp(self): """Set up app, session key, and fake client.""" app.config['TESTING'] = True self.client = app.test_client() connect_to_db(app, 'postgresql:///testdb') db.create_all()
def setUp(self): """before every test""" self.client = app.test_client() app.config['TESTING'] = True connect_to_db(app, 'postgresql:///testsubreddits') db.create_all() make_test_data()
def setUp(self): self.app = app.test_client() app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' app.config['TESTING'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.app = app db.init_app(app) db.create_all()
def setUp(self): # Connect to test database connect_to_db(app, "postgresql:///testdb") # Create tables and add sample data db.create_all() example_data()
def setUp(self): self.client = app.test_client() app.config['TESTING'] = True connect_to_db(app, "postgresql:///testdb") db.create_all() fake_data()
def setUp(self): """Set up app, session key, and db.""" app.config['TESTING'] = True # setup test db connect_to_db(app, 'postgresql:///testdb') db.create_all() populate_test_db_users()
def setUp(self): self.spotify = FakeSpotifyClient({ 'Prince': 'princeyprince' }) app.config['TESTING'] = True connect_to_db(app, "postgresql:///testdb") db.create_all() app.config['SQLALCHEMY_ECHO'] = False
def setUp(self): #: called before each individual test function is run application.app.config['SQLALCHEMY_DATABASE_URI'] = TEST_DATABASE_URI print '\n===> setup: using db -- ' + application.app.config['SQLALCHEMY_DATABASE_URI'] db.app = application.app self.app = application.app.test_client() db.create_all() #: initialize all tables MockUserData.static__init__() # initialize mock user data
def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() app.config['TESTING'] = True result = self.client.get("/my-route") connect_to_db(app, "postgresql:///reservationtonight") db.create_all()
def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() connect_to_db(app, "sqlite:///") db.create_all() example_data()
def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() app.config['TESTING'] = True connect_to_db(app, "postgresql:///testdb") db.create_all() example_data()
def setUp(self): """Set up database for testing purposes""" print "Setting up test database" self.app = app.test_client() app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:///testdb' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.app = app db.init_app(app) db.create_all()
def setUp(self): self.client = app.test_client() app.config["TESTING"] = True app.config["SECRET_KEY"] = "key" connect_to_db(app, db_uri="postgresql:///testdb") db.create_all() load_users(username="******", password="******")
def __init__(self): try: VNode.query.all() History.query.all() except: db.create_all(bind='__all__')
def test_create_schema(self): with app.test_request_context(): db.create_all()
import json from flask_cors import CORS app = Flask(__name__) CORS(app) app.config['SECRET_KEY'] = 'NTU_DB_2020_secret_key' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config[ 'SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@127.0.0.1:5432/dvdrental" db.init_app(app) with app.app_context(): db.drop_all() db.create_all() socketio = SocketIO(app, cors_allowed_origins='*') epoch = datetime.utcfromtimestamp(0) def unix_time_millis(dt): return (dt - epoch).total_seconds() * 1000.0 def generate_cookie(username, password, current_time): sha512 = hashlib.sha512() sha512.update(username.encode()) sha512.update(password.encode()) sha512.update(current_time.encode())
def init_db(): db.create_all()
from werkzeug.utils import secure_filename vote = Flask(__name__) Auth = auth() cache = Cache() ip = Ip() vote.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///VOOTE' #vote.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=True vote.config["SECRET_KEY"] = "6g73vut6svs766rdfd" vote.config['DATABASE'] = 'myblog.db' vote.config["UPLOAD_FOLDER"] = "/home/haibeeyy/mysite/uploads" Allowed_extensions = set(["png", "jpeg"]) db.init_app(vote) db.create_all(app=vote) per_query = 30 def onError(error=None): "returns some json object with error" if error: j_data = {"response": "error", "message": str(error)} else: j_data = {"response": "error", "message": "invalid parameters"} return jsonify(j_data) def json_message(response, message): return {"response": response, "message": message}
def setUp(self): setup_test_app_db() db.create_all() self.client = app.test_client() TmsApp() self.meet1 = Meet.init_meet(EXAMPLE_MEETS[0])
def setUp(self): self.client = app.test_client() app.config['TESTING'] = True connect_to_db(app, 'postgresql://*****:*****@localhost:5432/bike_test') db.create_all()
def createUserTable(): try: db.create_all() return json.dumps({'status': True}) except IntegrityError: return json.dumps({'status': False})
def setUp(self): setup_test_app_db() db.create_all() self.client = app.test_client() TmsApp()
def setUp(self): self.client = app.test_client() app.config['TESTING'] = True connect_to_db(app, "postgresql:///testdb") db.create_all()
def post(self): db.create_all() return {'message': 'Database initialization complete.'}
def create_user_table(): try: db.create_all() return json.dumps({'status': 'True'}) except IntegrityError: return json.dumps({'status': 'False'})
def clean_db(): # In case tables haven't been created, create them db.session.commit() db.drop_all() db.create_all()
def initialize_database(): db.create_all()
import hashlib import random import uuid from flask import Flask, render_template, request, make_response, redirect, url_for from model import User, db app = Flask(__name__) db.create_all() # create (new) tables in the database @app.route("/", methods=["GET"]) def index(): session_token = request.cookies.get("session_token") if session_token: user = db.query(User).filter_by(session_token=session_token).first() else: user = None return render_template("index.html", user=user) @app.route("/login", methods=["POST"]) def login(): name = request.form.get("user-name") email = request.form.get("user-email") password = request.form.get("user-password") # hash the password hashed_password = hashlib.sha256(password.encode()).hexdigest()
def create_db_command(): from sqlalchemy_utils import database_exists, create_database DB_URL = app.config['SQLALCHEMY_DATABASE_URI'] if not database_exists(DB_URL): create_database(DB_URL) db.create_all()
def setUp(self): """ Things to do before every test.""" # Get the Flask test client self.client = app.test_client() app.config['TESTING'] = True # Connect to test database connect_to_db(app, "postgresql:///testfood") # Create tables and add sample data db.drop_all() db.create_all() example_data() # Create a session app.config['SECRET_KEY'] = os.environ["testing_secret_key"] with self.client as c: with c.session_transaction() as sess: sess['user_id'] = 1 def _mock_recipe_info_by_id(recipe_id): """ Mock data of recipe info.""" return { "servings": 4, "preparationMinutes": 40, "sourceUrl": "testrecipe.com", "sourceName": "Test Source Recipe", "extendedIngredients": [{ "id": 1, "aisle": "Fruit", "image": "apple.png", "name": "apple", "amount": 1, "unit": "pound", "unitLong": "pound" }, { "id": 2, "aisle": "Fruit", "image": "banana.jpg", "name": "banana", "amount": 3, "unit": "ounces", "unitLong": "ounces" }], "id": 1, "title": "Test Recipe", "readyInMinutes": 60, "image": "/recipe.jpg", "instructions": "Recipe instructions here." } server.recipe_info_by_id = _mock_recipe_info_by_id model.recipe_info_by_id = _mock_recipe_info_by_id
def db_setup(cls): """Set up database for testing""" connect_to_db(app, TESTDB_URI) db.create_all()
def setUp(self): self.client = app.test_client() app.config['TESTING'] = True connect_to_db(app, 'postgresql:///bike_test') db.create_all() example_data()
def createDatabase(): database = CreateDB(hostname='mysqlserver') db.create_all() print("Database and table created")
def __init__(self, username='******', password=None): ''' Try to create the database when there is none initialize 'root' user and 'root' & 'primary' group ''' try: User.query.all() except: db.create_all() if password == None: #set a random password password = os.urandom(16) password = b64encode(password).decode('utf-8') fsdir = env.getenv('FS_PREFIX') f = open(fsdir + '/local/generated_password.txt', 'w') f.write("User=%s\nPass=%s\n" % (username, password)) f.close() sys_admin = User( username, hashlib.sha512(password.encode('utf-8')).hexdigest()) sys_admin.status = 'normal' sys_admin.nickname = 'root' sys_admin.description = 'Root_User' sys_admin.user_group = 'root' sys_admin.auth_method = 'local' db.session.add(sys_admin) path = env.getenv('DOCKLET_LIB') subprocess.call([path + "/userinit.sh", username]) db.session.commit() if not os.path.exists(fspath + "/global/sys/quota"): groupfile = open(fspath + "/global/sys/quota", 'w') groups = [] groups.append({ 'name': 'root', 'quotas': { 'cpu': '4', 'disk': '2000', 'data': '100', 'memory': '2000', 'image': '10', 'idletime': '24', 'vnode': '8' } }) groups.append({ 'name': 'admin', 'quotas': { 'cpu': '4', 'disk': '2000', 'data': '100', 'memory': '2000', 'image': '10', 'idletime': '24', 'vnode': '8' } }) groups.append({ 'name': 'primary', 'quotas': { 'cpu': '4', 'disk': '2000', 'data': '100', 'memory': '2000', 'image': '10', 'idletime': '24', 'vnode': '8' } }) groups.append({ 'name': 'foundation', 'quotas': { 'cpu': '4', 'disk': '2000', 'data': '100', 'memory': '2000', 'image': '10', 'idletime': '24', 'vnode': '8' } }) groupfile.write(json.dumps(groups)) groupfile.close() if not os.path.exists(fspath + "/global/sys/quotainfo"): quotafile = open(fspath + "/global/sys/quotainfo", 'w') quotas = {} quotas['default'] = 'foundation' quotas['quotainfo'] = [] quotas['quotainfo'].append({ 'name': 'cpu', 'hint': 'the cpu quota, number of cores, e.g. 4' }) quotas['quotainfo'].append({ 'name': 'memory', 'hint': 'the memory quota, number of MB , e.g. 4000' }) quotas['quotainfo'].append({ 'name': 'disk', 'hint': 'the disk quota, number of MB, e.g. 4000' }) quotas['quotainfo'].append({ 'name': 'data', 'hint': 'the quota of data space, number of GB, e.g. 100' }) quotas['quotainfo'].append({ 'name': 'image', 'hint': 'how many images the user can save, e.g. 10' }) quotas['quotainfo'].append({ 'name': 'idletime', 'hint': 'will stop cluster after idletime, number of hours, e.g. 24' }) quotas['quotainfo'].append({ 'name': 'vnode', 'hint': 'how many containers the user can have, e.g. 8' }) quotafile.write(json.dumps(quotas)) quotafile.close() if not os.path.exists(fspath + "/global/sys/lxc.default"): settingfile = open(fspath + "/global/sys/lxc.default", 'w') settings = {} settings['cpu'] = "2" settings["memory"] = "2000" settings["disk"] = "2000" settingfile.write(json.dumps(settings)) settingfile.close() try: UserUsage.query.all() except: db.create_all()
# db.session.commit() # print "Successfully added task: {}".format(task_name) # @app.route('/googlecalendar', methods=['GET']) # def google_map(): # return render_template("index-test.html") # @app.route('/testing') # def test_page(): # return render_template("testpage.html") ################### Helper Functions ####################### if __name__ == "__main__": app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False #Set debug=True in order to invoke the DebugToolbarExtension app.debug = True # app.config['TRAP_HTTP_EXCEPTIONS'] = True DebugToolbarExtension(app) connect_to_db(app) db.create_all(app=app) app.run(port=5000, debug=True, host='0.0.0.0')
def migrate(): '''Creates all tables in the database''' from model import db click.echo('Creating Tables') db.create_all() click.echo('All Tables are created')
def setUp(self): self.db_fd, app.config['medicines'] = tempfile.mkstemp() self.app = app.test_client() connect_to_db(app, "sqlite:///") db.create_all()
def checkcrime(ctx, lat, lon, radius): # database = CreateDB(hostname = 'localhost') engine = sqlalchemy.create_engine('mysql://%s:%s@%s' % (USER, PASSWORD, HOSTNAME)) engine.execute("DROP DATABASE IF EXISTS %s " % (DATABASE)) engine.execute("CREATE DATABASE IF NOT EXISTS %s " % (DATABASE)) db.create_all() # Get Raw data from api.spotcrime. Store it in JSON format in cjdata cjdata = json.load( urllib2.urlopen( 'https://api.spotcrime.com/crimes.json?lat=%s&lon=%s&radius=%s&key=.' % (lat, lon, radius))) cjcrimes = cjdata['crimes'] print 'cjcrimes is', cjcrimes no_of_crimes = len(cjcrimes) for i in range(0, no_of_crimes): crime_type = cjcrimes[i]['type'] crime_address = str(cjcrimes[i]['address']) crime_street = crime_address if 'BLOCK' in crime_address: if 'BLOCK BLOCK' in crime_address: temp = crime_address.split('BLOCK BLOCK ') crime_street = str(temp[1]) elif 'BLOCK OF' in crime_address: temp = crime_address.split('BLOCK OF ') crime_street = str(temp[1]) elif 'BLOCK' in crime_address: temp = crime_address.split('BLOCK ') crime_street = str(temp[1]) else: crime_street = crime_address crime_timestamp = cjcrimes[i]['date'] struct_time = time.strptime(crime_timestamp, "%m/%d/%y %I:%M %p") if struct_time.tm_hour == 1 or struct_time.tm_hour == 2: crime_time = '12:01am-3am' if struct_time.tm_hour == 3: if struct_time.tm_min == 0: crime_time = '12:01am-3am' else: crime_time = '3:01am-6am' if struct_time.tm_hour == 4 or struct_time.tm_hour == 5: crime_time = '3:01am-6am' if struct_time.tm_hour == 6: if struct_time.tm_min == 0: crime_time = '3:01am-6am' else: crime_time = '6:01am-9am' if struct_time.tm_hour == 7 or struct_time.tm_hour == 8: crime_time = '6:01am-9am' if struct_time.tm_hour == 9: if struct_time.tm_min == 0: crime_time = '6:01am-9am' else: crime_time = '9:01am-12noon' if struct_time.tm_hour == 10 or struct_time.tm_hour == 11: crime_time = '9:01am-12noon' if struct_time.tm_hour == 12: if struct_time.tm_min == 0: crime_time = '9:01am-12noon' else: crime_time = '12:01pm-3pm' if struct_time.tm_hour == 13 or struct_time.tm_hour == 14: crime_time = '12:01pm-3pm' if struct_time.tm_hour == 15: if struct_time.tm_min == 0: crime_time = '12:01pm-3pm' else: crime_time = '3:01pm-6pm' if struct_time.tm_hour == 16 or struct_time.tm_hour == 17: crime_time = '3:01pm-6pm' if struct_time.tm_hour == 18: if struct_time.tm_min == 0: crime_time = '3:01pm-6pm' else: crime_time = '6:01pm-9pm' if struct_time.tm_hour == 19 or struct_time.tm_hour == 20: crime_time = '6:01pm-9pm' if struct_time.tm_hour == 21: if struct_time.tm_min == 0: crime_time = '6:01pm-9pm' else: crime_time = '9:01pm-12midnight' if struct_time.tm_hour == 22 or struct_time.tm_hour == 23: crime_time = '9:01pm-12midnight' if struct_time.tm_hour == 0: if struct_time.tm_min == 0: crime_time = '9:01pm-12midnight' else: crime_time = '12:01am-3am' # Have entries to put in the database. # Need to put crime_type, crime_street and crime_time. # Should add a try, except user = User(crime_street, crime_type, crime_time) db.session.add(user) #for loop should end here db.session.commit() engine.execute('use %s;' % (DATABASE)) # Top three streets with most crime results_streets = engine.execute( 'select street, count(*) as crime from user group by street order by crime DESC limit 3;' ) top_three_streets = [] for row in results_streets: top_three_streets.append(row.street) # Collecting numbers of crime types and time of crimes assault = engine.execute( "select count(type) as count from user where type='Assault';") for row in assault: assault_count = row.count arrest = engine.execute( "select count(type) as count from user where type='Arrest';") for row in arrest: arrest_count = row.count burglary = engine.execute( "select count(type) as count from user where type='Burglary';") for row in burglary: burglary_count = row.count robbery = engine.execute( "select count(type) as count from user where type='Robbery';") for row in robbery: robbery_count = row.count theft = engine.execute( "select count(type) as count from user where type='Theft';") for row in theft: theft_count = row.count other = engine.execute( "select count(type) as count from user where type='Other';") for row in other: other_count = row.count time_12am_3am = engine.execute( "select count(type) as count from user where time='12:01am-3am';") for row in time_12am_3am: time_12am_3am_count = row.count time_3am_6am = engine.execute( "select count(type) as count from user where time='3:01am-6am';") for row in time_3am_6am: time_3am_6am_count = row.count time_6am_9am = engine.execute( "select count(type) as count from user where time='6:01am-9am';") for row in time_6am_9am: time_6am_9am_count = row.count time_9am_12pm = engine.execute( "select count(type) as count from user where time='9:01am-12noon';" ) for row in time_9am_12pm: time_9am_12pm_count = row.count time_12pm_3pm = engine.execute( "select count(type) as count from user where time='12:01pm-3pm';") for row in time_12pm_3pm: time_12pm_3pm_count = row.count time_3pm_6pm = engine.execute( "select count(type) as count from user where time='3:01pm-6pm';") for row in time_3pm_6pm: time_3pm_6pm_count = row.count time_6pm_9pm = engine.execute( "select count(type) as count from user where time='6:01pm-9pm';") for row in time_6pm_9pm: time_6pm_9pm_count = row.count time_9pm_12am = engine.execute( "select count(type) as count from user where time='9:01pm-12midnight';" ) for row in time_9pm_12am: time_9pm_12am_count = row.count result_output = json.dumps({ 'total crime': no_of_crimes, 'the_most_dangerous_streets': top_three_streets, 'crime_type_count': { 'Assault': assault_count, 'Arrest': arrest_count, 'Burglary': burglary_count, 'Robbery': robbery_count, 'Theft': theft_count, 'Other': other_count }, 'event_time_count': { '12:01am-3am': time_12am_3am_count, '3:01am-6am': time_3am_6am_count, '6:01am-9am': time_6am_9am_count, '9:01am-12noon': time_9am_12pm_count, '12:01pm-3pm': time_12pm_3pm_count, '3:01pm-6pm': time_3pm_6pm_count, '6:01pm-9pm': time_6pm_9pm_count, '9:01pm-12midnight': time_9pm_12am_count } }) yield result_output
def upload_file(billId): start = time.time() bill_id = billId username = request.authorization.username passwordinfo = request.authorization.password bill_sc = Billschema(many=False) data1 = request.get_json() dbtime = time.time() flag = checkauthentication(username, passwordinfo) dur = (time.time() - dbtime) * 1000 c.timing("dbconnect", dur) if flag == True: #check if user exits result = Credential.select_user_by_email(username) user_sc = Credentialschema() data = user_sc.dump(result) owner_id = data.get('id') dbtime = time.time() result2 = Bills.select_user_by_billid(bill_id) dur = (time.time() - dbtime) * 1000 c.timing("dbconnect", dur) bill_sc = Billschema(many=False) data2 = bill_sc.dump((result2)) owner_id2 = data2.get('owner_id') if owner_id == owner_id2: #authorized against bill and user # checking if the request has the file part file = request.files['file'] # if 'file' not in request.files: return custom_http_code('No file part in the request', 400) elif file.filename == '': return custom_http_code('No file part in the request', 400) elif file and allowed_file(file.filename): result = File.select_file_by_billid(bill_id) print(result) if result: return custom_http_code( "file already exists with bill delete first", 400) filename = secure_filename(file.filename) id = str(uuid.uuid4().hex) dir = "attachments" + "/" + id # os.mkdir(dir) target = os.path.join(root_dir, dir) print(target) if not os.path.isdir(target): os.mkdir(target) else: return custom_http_code("file already exists", 400) destination_folder = "/".join([target, filename]) file.seek(0, os.SEEK_END) file_len = file.tell() img_key = hashlib.md5(file.read()).hexdigest() obj = file.save(destination_folder) #file = request.files['file'] object_name = id + "/" + file.filename s3_client = boto3.client('s3') name = 'attachments/' + id + '/' + filename #fileobj= open(name,'r') #obj=file.save(destination_folder) file = request.files['file'] dbtime = time.time() uploading = s3_client.upload_fileobj(file, bucket, object_name) #obj=file.save(destination_folder) dur = (time.time() - dbtime) * 1000 c.timing("s3time", dur) url = 'https://s3.console.aws.amazon.com/' + bucket + "/attachments/" + id + "/" + filename upload_date = datetime.datetime.today().strftime('%Y-%m-%d') # img_key = hashlib.md5(file.read()).hexdigest() # print(img_key.encode("utf-8")) dbtime = time.time() new_bill = File(id, bill_id, filename, upload_date, url, file_len, img_key) db.create_all() db.session.add(new_bill) db.session.commit() dur = (time.time() - dbtime) * 1000 c.timing("dbconnect", dur) # result=Credential.query.filter_by(first_name='Jane').first() file_sc = File_schema_output(many=False) result = File.select_file_by_file_id(id) print(result) data = file_sc.dump(result) print(data) # bill_schema= Billschema(many=False) # data= Bills.select_user_by_billid(billid) # query_result = bill_schema.dump(data) #file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) c.incr("postfilecount") dur = (time.time() - start) * 1000 c.timing("postfilecount", dur) return custom_http_code(data, 201) else: c.incr("postfilecount") dur = (time.time() - start) * 1000 c.timing("postfilecount", dur) return custom_http_code('wrong file extension', 400) else: c.incr("postfilecount") dur = (time.time() - start) * 1000 c.timing("postfilecount", dur) return custom_http_code('Unauthorised', 401) else: return custom_http_code('invalid login', 401)
def page(): start = time.time() db.create_all() user_sc = Credentialschema(many=False) dur = (time.time() - start) * 1000 c.timing("dbconnect", dur) data = request.get_json() check_email = data.get('email_address') check_pass = data.get('password') #check if valid email def check(emailid): regexp = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' if re.search(regexp, emailid): return True else: return False flagging = check(check_email) def checkpass(passwd): if len(passwd) <= 7: return False elif not re.search("[A-Z]", passwd): return False elif not re.search("[0-9]", passwd): return False return True flagging1 = checkpass(check_pass) dbtime = time.time() if Credential.select_user_by_email(check_email): dur = (time.time() - dbtime) * 1000 c.timing("dbconnect", dur) return custom_http_code('Bad resquest', 400) if flagging == False or flagging1 == False: return custom_http_code('Bad request', 400) else: load_data = user_sc.load(data) new_user = Credential(load_data) # Credential.execute_query() dbtime = time.time() db.session.add(new_user) db.session.commit() dur = (time.time() - dbtime) * 1000 c.timing("dbconnect", dur) # result=Credential.query.filter_by(first_name='Jane').first() result = Credential.select_user_by_email(check_email) print(result) data = user_sc.dump(result) print(data) # output=Credential.select_user_by_email(check_email) print("done") c.incr("createuser") dur = (time.time() - start) * 1000 c.timing("createusertime", dur) return jsonify(data)
def setup_database(app): with app.app_context(): db.create_all()
finn.user_cities.extend([finn_sf, finn_london, finn_taipei]) db.session.add(finn) db.session.commit() # ====================================== # MAIN SCRIPT # ====================================== os.system('dropdb looksee') os.system('createdb looksee') connect_to_db(server.app) db.create_all() # setup tables # add real countries # ================== res_country_dict = api_fx.sherpa_all_countries() countries = res_country_dict["data"] # for each country item in response, # add a record to country db table for c in countries: ccode = c["attributes"]["isoAlpha3"] cname = c["attributes"]["countryName"] cadd = crud.add_country(ccode, cname) print(f"adding country {cadd}") db.session.add(cadd)
def init_db(): with app.app_context(): db.session.commit() db.drop_all() db.create_all()