Example #1
0
def create(config):
    """http://flask.pocoo.org/docs/patterns/appfactories/"""

    app = Flask(__name__.split('.')[0])

    # Load YAML config into app.config
    if not isinstance(config, dict):
        with open(os.path.join(app.instance_path, config)) as f:
            config = yaml.load(f)
    config.update({k.upper(): v for k, v in config["flask"].items()})
    app.config.update(config)
    del config
    
    # Configure logging
    logging.config.dictConfig(app.config["logging"])

    # Initialize database
    app.database = Database(app)

    # Load blueprints
    from .views.submit import submit
    app.register_blueprint(submit)

    if False and app.debug:
        app.logger.warning("Debug mode is on. Do not use this in production.")
        from .views.debug import debug
        app.register_blueprint(debug)

    return app
Example #2
0
from flask import Flask, render_template, redirect, url_for, request, session, flash, g, Blueprint, abort
from jinja2 import TemplateNotFound
from flask.json import jsonify
from functools import wraps
from flask.ext.sqlalchemy import SQLAlchemy
import sqlite3

from views.header import header

app = Flask(__name__)

app.register_blueprint(header.header)

app.secret_key = "my precious"
app.database = 'testjwz.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
#app.config.from_object(os.environ['APP_SETTINGS'])
from models import *
db = SQLAlchemy(app)

def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login'))
    return wrap
    
@app.route('/', methods=['GET', 'POST'])
Example #3
0
from flask import Flask, render_template, redirect, url_for, request, session, flash, g
from functools import wraps
import sqlite3

app = Flask(__name__)

# configuration variable
app.secret_key = 'my password'
app.database = "sample.db"


# login required decorator
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login'))
    return wrap

# set up first route with a decorator 

@app.route('/')
@login_required 
def home():
    #return "Hello world"
    # g is specific to flask to store a temporary task
    g.db = connect_db() # this creates the connection object
    cur = g.db.execute('select * from posts')
Example #4
0
File: app.py Project: zesk06/scores
    FILE_URI = os.path.join(THIS_DIR, 'target/scores.yml')
    DATABASE_URI = 'mongodb://<dbuser>:<dbpassword>@<instance>.mlab.com:<port>/<dbname>_test'
    if 'TEST_DATABASE_URI' in os.environ:
        DATABASE_URI = os.environ['TEST_DATABASE_URI']


app = Flask(__name__)
app.config.from_object(Config)

# used by flask-login
app.secret_key = 'idontwanttobeinthepubliccode'
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

app.database = None


def get_db():
    """Return the Database
    :rtype: database.Database"""
    if app.database is None:
        print('connecting to %s' % app.config['DATABASE_URI'])
        app.database = database.Database(app.config['DATABASE_URI'])
    return app.database


@login_manager.user_loader
def user_loader(login):
    # retrieve user from database
    print('user_loader')
Example #5
0
from flask import Flask, render_template, redirect, url_for, request, session, flash, g
from functools import wraps
import sqlite3


app = Flask(__name__)

app.secret_key = "my precious"
app.database = "flask.db"


def login_required(test):
	@wraps(test)
	def wrap(*args, **kwargs):
		if 'logged_in' in session:
			return test(*args, **kwargs)
		else:
			flash('You need to login first.')
			return redirect(url_for('login'))
	return wrap

@app.route('/')
@login_required
def home():
        g.db = connect_db()
        query = g.db.execute('SELECT * FROM posts')
        posts = [dict(title=row[0], description=row[1]) for row in query.fetchall()]
        g.db.close()
        return render_template('index.html',posts=posts)

@app.route('/welcome')
Example #6
0
# import the Flask class from the flask module
from flask import Flask, render_template, redirect, url_for, request, session, flash
from functools import wraps
import sqlite3
from Classes import *
from pony.orm import *
import bcrypt


# create the application object
app = Flask(__name__)

app.secret_key = "tomato"
app.database = "notice_db.db"


def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('Access denied: You must login first.')
            return redirect(url_for('login'))
    return wrap


# use decorators to link the function to a url
@app.route('/', methods=['GET', 'POST'])
@db_session
def login():
Example #7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-


from flask import Flask, render_template, redirect, url_for, request, session, flash, g
from functools import wraps
import sqlite3

app = Flask(__name__)
app.secret_key = 'a secret key'
app.database = 'blog.db'

def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('Enter username and password.')
            return redirect(url_for('login'))
    return wrap

@app.route('/')
@login_required
def home():
    g.db = connect_db()
    cur = g.db.execute('select * from posts')
    posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
    g.db.close()
    return render_template('index.html', posts=posts)  
    
Example #8
0
	str = unicode

psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)



app = Flask(__name__)
app.config.from_object(os.environ['SDV_APP_SETTINGS'].strip('"'))
recaptcha = ReCaptcha(app=app)
app.secret_key = app.config['SECRET_KEY']
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.wsgi_app = ProxyFix(app.wsgi_app)
if app.config['USE_SQLITE'] == True:
	app.database = app.config['DB_SQLITE']
	app.sqlesc = '?'
	def connect_db():
		return sqlite3.connect(app.database)
else:
	app.database = 'dbname='+app.config['DB_NAME']+' user='+app.config['DB_USER']+' password='+app.config['DB_PASSWORD']
	app.sqlesc = '%s'
	def connect_db():
		return psycopg2.connect(app.database)

def md5(md5file):
	h = hashlib.md5()
	if type(md5file) == io.BytesIO:
		h.update(md5file.getvalue())
	else:
		for chunk in iter(lambda: md5file.read(4096), b""):
Example #9
0
import re
import time

# labels: list
# data list
from multiprocessing import Process

# Private - utils is the regex, redditBot is the bot class, redditDatabase is the actually storing and extracting from database
from scripts import utils, redditBot, redditDatabase

# create application object
app = Flask(__name__)
# change database name later
app.database =  {
    'database': 'reddit_data',
    'user': 'reddit_data',
    'password': 'reddit_data',
    'host': 'localhost'
}
# secret key for cookies *MUST CHANGE FOR SECURITY*
app.secret_key = b'\xd0\x10\x0b$\x0fk\xbe%\xc6\x1b\xe4\xd1\xf0\xe0\xd4\x0210\xc5R\x80X\x98+'

# landing page with text field
# route() decorator to tell Flask what URL should trigger our function.
@app.route('/', methods=['GET', 'POST'])
def home():
    error = None
    if request.method == 'POST':
        session['url'] = request.form['url'] #storing this information while the user is browsing
        session['isBotOn'] = False #bot isn't on yet
        if (utils.getPostID(session['url']) == False):
            error = "You're tripping! Enter a reddit post URL!"
Example #10
0
from flask import Flask, g, render_template, redirect, request, url_for, session, flash
from functools import wraps
import sqlite3
from datetime import datetime
import urllib

app = Flask(__name__)
app.secret_key = "not a good secret"
app.database = "blog.db"
app.config['DEBUG'] = True


def connect_db():
    return sqlite3.connect(app.database)


def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            return redirect(url_for('login'))
    return wrap


@app.route('/')
@app.route('/index')
def index():
    g.db = connect_db()
    cur = g.db.execute('SELECT * FROM posts WHERE pub_status="published" ORDER BY `date_posted` DESC')
Example #11
0
from flask import Flask


app = Flask(__name__)
app.database = 'WODTracker.db'
app.debug = True
app.secret_key = 'dev'
# Setup database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///WODTracker.db'

import WODTracker.views
from views import *

app.add_url_rule('/',
	view_func=Index.as_view('index'),
	methods=['GET','POST'])
app.add_url_rule('/newuser',
	view_func=NewUser.as_view('new_user'),
	methods=['GET','POST'])
app.add_url_rule('/recordworkout',
	view_func=WorkoutView.as_view('workout'),
	methods=['GET','POST'])
app.add_url_rule('/newexercise',
	view_func=ExerciseView.as_view('new_exercise'),
	methods=['GET','POST'])
app.add_url_rule('/weighin',
	view_func=WeighInView.as_view('weighin'),
	methods=['GET','POST'])
app.add_url_rule('/calendar',
	view_func=CalendarView.as_view('calendar'),
	methods=['GET'])
Example #12
0
from mapping_model import Property, Image
from sqlalchemy.orm import scoped_session, sessionmaker, Query
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import join



app = Flask(__name__)


#Next was the original database
#app.database = "realstate.db"
#Next is the database created with flask admin
app.database = "propertyRS.db"

app.secret_key = "xcFtjs3Ji896Ghm"

#Next lines are for SQL Alchemy use
engine = create_engine("sqlite:////tmp/propertyRS.db")
Base = declarative_base()
Base.metadata.reflect(engine)



@app.route('/', methods=['GET', 'POST'])
def home():
	if request.method == 'POST':		
		if request.form['state'] != "" :	
			stateValue = request.form['state']
Example #13
0
from flask import Flask, render_template, g
#Import SQLlite for database
import sqlite3

app = Flask(__name__)

#Setup Database
app.database = "M2MWebsite/sample.db"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/team/')
def team():
    return render_template('team.html')

@app.route('/prototype/')
def prototype():
    return render_template('prototype.html')

@app.route('/users/')
def users():
    #Create temporary connection object
    g.db = connect_db()
    #query the database
    cur = g.db.execute('select * from users')
    #Cast data to dictionary
    users = [dict(id=row[0],cardID=row[1],name=row[2],credit=row[3],bottles=row[4]) for row in cur.fetchall()]
    #Close database connection
    g.db.close()
Example #14
0
from flask import Flask, render_template, url_for, g
import sqlite3

app = Flask(__name__)

app.database = "familjen.db"


def connect_db():
	return sqlite3.connect(app.database)

@app.route('/')
def home():
	return render_template('home.html')

@app.route('/members')
def members():
	g.db = connect_db()
	cur = g.db.execute('select * from members')
	members = [dict(imageref=row[0], name=row[1], about=row[2], joined=row[3]) for row in cur.fetchall()]
	g.db.close()
	return render_template('members.html', members = members)

@app.route('/info')
def info():
	return render_template('info.html')

@app.route('/activities')
def activities():
	g.db = connect_db()
	cur = g.db.execute('select * from parties')
Example #15
0
from flask import Flask, jsonify, render_template, request, g, redirect, request
import sqlite3, json

app = Flask(__name__)
app.database = "chart_data.db"
entries = ""
def connect_db():
	return sqlite3.connect(app.database)


@app.route('/', methods=['POST'])
def index():
		#getdata()
		g.db = connect_db()
		#g.db.execute('insert into ghosts (title, description) values (?, ?)',[request.form['title'], request.form['description']])
		g.db.execute('insert into chart_table (name,test_value) values ("Shreyas","23")')
		cur = g.db.execute('select * from chart_table')
		entries = [dict(test_value=row[1],name=row[0]) for row in cur.fetchall()]
		g.db.close()
		#print entries

		with open("static\chartson.json","w") as outfile:
			json.dump(
			entries,outfile) #

		return render_template('index.html', entries=entries)



if __name__ == '__main__':
    app.run(debug=True)
Example #16
0
from flask import Flask, flash, redirect, render_template, g, request, url_for
import sqlite3

app = Flask(__name__)
app.database = "blog_posts.db"
app.secret_key = 'super spooky secret key'

# A list of words and their corresponding translations for our app
# words = {"Bonjour": "hello", "Jambon": "ham", "Fromage": "cheese"}


@app.route('/')
def index():
    return render_template("index.html")

@app.route('/france', methods=['GET', 'POST'])
def france():
    g.db = connect_db()
    cur = g.db.execute("select * from words where language= ?", ("French",))
    words = [dict(word=row[0], translation=row[1]) for row in cur.fetchall()]
    g.db.close()
    print(words)
    points = 0
    if request.method == "POST":
        for word, translation in words.items():
            if request.form[word] == translation:
                points += 1
        flash(str(points))
        return redirect(url_for('france'))
    return render_template("france.html", words=words)
Example #17
0
#!/usr/bin/env python
# -*- Coding: Utf-8 -*-

"""
IS211 Assignment 13: Flask web dev part II
"""

import sqlite3

from flask import Flask, render_template, request, redirect, url_for, g

app = Flask(__name__)

app.database = 'hw13.db'


@app.route('/')
def start():
    """
    First page
    """
    return redirect('/login')


@app.route('/login', methods=['GET', 'POST'])
def login():
    """
    Login form processing
    On success: go to /dashboard
    On fail: Go to /login with error
    """
Example #18
0
from functools import wraps
import sqlite3
import os
from config import Config # import the Config class from module config
# 



# create the application object
app = Flask(__name__)

# app.config.from_object(os.environ['APP_SETTINGS']) # application configuration
app.config.from_object('config')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
app.database = "posts.db"
app.secret_key = "This-is-confidential"


# create the app with security default login being profile route
# app.config['SECURITY_POST_LOGIN'] = '/profile'

# create and config the database object
db = SQLAlchemy(app)

from models import *

# gthub oauth configuration
# client_id = app.config['GITHUB_CLIENT_ID']
# client_secret = app.config['GITHUB_CLIENT_SECRET']
Example #19
0
from flask import Flask, render_template, redirect, url_for, request, session, flash, g, Markup
from functools import wraps
from subprocess import check_output
from hashlib import sha256
from uuid import uuid4
import sqlite3


app = Flask(__name__)

app.config.from_object('config')
app.database = app.config['DATABASE']
app.script = app.config['SCRIPT']
app.secret_key = app.config['SECRET_KEY']

###################################### NON-PAGE FUNCTIONS ###################################

##
# Login Required Decorator
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You must be logged in to view this page.')
            return redirect(url_for('login'))
    return wrap

##
# Admin Required Decorator
Example #20
0
File: hi.py Project: ahdrage/flask
from flask import Flask, render_template, redirect, url_for, request, g 
import sqlite3


app = Flask(__name__)
app.database = "toplist.db"



@app.route('/')
def home():
   
    return render_template('index.html')


@app.route('/result')
def result():
    g.db = connect_db()
    cur = g.db.execute('select * from listing')
    listing = [dict(Year=row[0], Week=row[1], Artist=row[2], Title=row[3], SpotUrl=row[4], SpotID=row[5], Image=row[6]) for row in cur.fetchall()]
  
    g.db.close()
    return render_template('result.html', listing=listing)


def connect_db():
	return sqlite3.connect(app.database)



Example #21
0
from flask import Flask, request, render_template, g
import sqlite3 as sl
import os
from twilio.rest import TwilioRestClient

app = Flask(__name__)

sec_k = os.urandom(24)
app.secret_key = sec_k

app.database = "reg.db"

@app.route('/')
def index():
	return render_template('index.html')

@app.route('/subscribe')
def subscribe():
	return render_template('subscribe.html')

@app.route('/request_handler', methods=['GET', 'POST'])
def request_handler():
	name = request.form['yourname']
	email = request.form['youremail']
	num = request.form['yournum']
	g.db = connect_db()
	params = (str(name), str(email), str(num))
	curr = g.db.cursor()
	curr.execute("INSERT INTO registrations VALUES (?, ?, ?)", params)
	cur = g.db.execute('SELECT * FROM registrations')
	regs = [dict(name=row[0], email=row[1], phone=row[2]) for row in cur.fetchall()]
    date    :   10/24/15
    project :   Independent

"""

# import the modules we need
import os
import sqlite3

from flask import Flask, render_template, request, g

# Create the recipesnremedieslication object
recipesnremedies = Flask(__name__)
# recipesnremedies.debug = True
# Add in a configuration variable for the database, assign
recipesnremedies.database = "cookbook.db"

# use decorators to link the function to a url
@recipesnremedies.route('/', methods=['GET', 'POST'])
def home():
    """ Function for flask interaction with the html webpage - homepage or index"""

    try:
        # g is a temp object specific to flask and it stores the database 
        # connection in this case
        # this value is reset after each request use it to connect and store
        # the db object
        g.db = connect_db()
        cur= g.db.execute('SELECT * FROM recipes')
        
        # cast the data to a dictionary
Example #23
0
from functools import wraps
import sqlite3
import os
app = Flask(__name__)
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login'))
    return wrap

app.secret_key = os.urandom(24)
app.database='sample.db'
conn=sqlite3.connect('sample.db')


@app.route('/welcome')
@login_required
def welcome():
 return render_template('welcome.html')

@app.route('/home')
@login_required
def home():
 return render_template('home.html')

@app.route('/sef')
def sef():
Example #24
0
import time
from flask import Flask,  redirect, url_for, request, jsonify
from functools import wraps 
import json

app = Flask(__name__)
app.database = './messages.db'
app.secret_key = 'CucumberSec'

from views import *

if __name__ == "__main__":
    app.run(debug=True)


# import the Flask class from the flask module
from flask import Flask, render_template, redirect, url_for, request, session, flash, g, Markup
from pymongo import MongoClient
from textblob import TextBlob
import plotly.plotly as py
import numpy as np
import plotly.graph_objs as go
from plotly import tools
import plotly.tools as tls
py.sign_in('nashc', '3nzdm0kuzk')


# create the application object
app = Flask(__name__)
app.database = 'press'
app.collection = 'mini1'

def textblob_sentiment(text):
	'''
		Use TextBlog package to get sentiment values for each press release text
		
		INPUT:
		- text: release text string

		OUTPUT:
		- (polarity, subjectivity): tuple containing the sentiment values
	'''
	#create TextBlog object and use inherent methods to get polarity and subjectivity
	blob = TextBlob(text)
	polarity = blob.sentiment.polarity
Example #26
0
import sqlite3
import string
import urllib2
from math import floor
from sqlite3 import OperationalError
from urlparse import urlparse

from BeautifulSoup import BeautifulSoup
from flask import Flask, request, render_template, redirect, flash

host = 'http://localhost:5000/'

app = Flask(__name__)
app.database = 'example.db'
app.secret_key = 'super secret key'


def createTable():
    create_table = '''CREATE TABLE IF NOT EXISTS WEB_URL (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        url string NOT NULL UNIQUE,
        short string,
        hits INT,
        t TIMESTAMP
        DEFAULT CURRENT_TIMESTAMP,
        title string
        ); '''

    with sqlite3.connect('example.db') as conn:
        cursor = conn.cursor()
        try:
Example #27
0
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from apscheduler.schedulers.background import BackgroundScheduler
import sqlite3 as lite
from webCrawler import getAllFoods
from contextlib import closing
from flask_mail import Mail, Message


app = Flask(__name__)

app.config.from_object(__name__)
app.config["DEBUG"] = True
app.database = "WhatsCookin\'.db"

app.config.update(
DEBUG = True,
MAIL_SERVER = 'smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USERNAME = 'smellzgud@gmail.com',
MAIL_PASSWORD = 'Columbia'
)
#Create mail object
mail = Mail(app)
app.config.from_object(__name__)

#Create the database------------------------------------------------------------
def connect_db():
	return lite.connect(app.database)

#Creates the database if it doesnt exist
Example #28
0
from flask import Flask, g, session, render_template, jsonify, request, redirect, url_for
import databaseservice
from users import Users, confirmed_password_valid
from gamebuilder import GameBuilder
from gameengine import GameEngine
from gameconfigurations import save_internet_game

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = \
    '\xd1\xd1\xb9H\xb6\x0e\x0f\xc3*\xb7\xef\xe7\x02GZ\xd1\xeb\xe4\xcd\xa1\x86c2k'
app.database = 'adventure_game.db'

def connect_database():
  """ Connect to app.database and return the connection object. """
  return databaseservice.connect_database(app.database)

def initialize_database():
  """ Initialize the database. """
  with app.open_resource('schema.sql') as schema:
    databaseservice.initialize_database(app.database, schema)

@app.before_request
def before_request():
  """ open dictionary/db connection"""
  database_connection = connect_database()
  database_cursor = database_connection.cursor()
  g.database_service = databaseservice.DatabaseService( \
      database_connection, database_cursor)

Example #29
0
from flask import Flask, render_template, request, g
app = Flask(__name__)

import inspect, os
app.database = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/propcalc.db'
import sqlite3
def connect_to_database():
	return sqlite3.connect(app.database)

@app.route("/")
def main():
	g.db = connect_to_database()
	current = g.db.execute('select * from subjects')
	subjects = current.fetchall()
	return render_template('my_properties.html', subjects=subjects)

import ast
@app.route("/edit_property/<subject>")
def edit_property(subject):
	subject = ast.literal_eval(subject)
	return render_template('edit_property.html', subject=subject)

from lib.prop_calc import *
@app.route('/sales_approach/<subject>', methods=['GET', 'POST'])
@app.route('/sales_approach/', defaults={'subject': None}, methods=['GET', 'POST'])
def sales_approach(subject):
	if request.method == 'POST':
		subject = {}
		for field in request.form:
			subject[field] = request.form[field]
		subject['address'] = subject['street'] + ' ' + subject['city'] + ', ' + subject['state'] + ' ' + subject['zipcode']
Example #30
0
from flask import Flask, flash, g, session, \
	redirect, render_template, request, url_for
import sqlite3


app = Flask(__name__)

app.secret_key = "secret"
app.database = "database.db"



@app.route('/')
def index():
	g.db = connect_db()
	cur = g.db.execute('SELECT * FROM posts')
	posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
	g.db.close()
	return render_template('index.html', posts=posts)


@app.route('/login/', methods = ["GET", "POST"])
def login():
	error = None
	if request.method == "POST":
		lg = request.form['username']
		pw = request.form['password']
		g.db = connect_db()
		cur = g.db.execute('SELECT * FROM users')
		users_dict = [dict(login=row[0], password=row[1]) for row in cur.fetchall()]
		g.db.close()