def start(port): app.debug = app.config['DEBUG'] or False if app.debug: # does not watch for changes and recompile on requests if debug false Scss(app, static_dir='application/static/css', asset_dir='application/assets/scss/manifest', load_paths=[path.join(path.dirname(__file__), 'assets/scss')]) app.run('0.0.0.0', port=port)
#! /usr/bin/env python2 from mysite import app if __name__ == '__main__': app.debug = True try: from flask.ext.scss import Scss Scss(app, static_dir="mysite/static/css", asset_dir="mysite/static/scss") except ImportError: print("Not compiling scss, not installed.") app.run(host="0.0.0.0")
import os from flask import Flask from flask import render_template from flask.ext.scss import Scss app = Flask(__name__) app.debug = True Scss(app, static_dir='static/css', asset_dir='assets/scss') @app.route('/') def hello(): return render_template('index.html', name="turtlea") if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from flask.ext.scss import Scss app = Flask(__name__) Scss(app, static_dir='static', asset_dir='assets') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///hello.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) posts = db.relationship('Post', backref='user', lazy=True) # 複数の Post への紐付け def __init__(self, username, posts=[]): self.username = username self.posts = posts # ユーザ追加時は基本的に空だと思いますが、念のため追加できるようにしておく # Post クラスを追加 class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(120), nullable=False) body = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) # 一人の User への紐付け def __init__(self, title, body, user_id):
import sys from flask import Flask from flask import render_template from flask.ext.scss import Scss from flask_frozen import Freezer import data app = Flask(__name__) freezer = Freezer(app) # configure flask extensions _scss = Scss(app, static_dir='static', asset_dir='assets') @app.route('/') def hello_world(): raw_data = data.get_survey_responses() categories = data.get_categories() chosen_options = get_chosen_options(raw_data) return render_template('index.html', raw_data=raw_data, categories=categories, chosen_options=chosen_options) def get_chosen_options(raw_data): #get unique options with sets chosen_options = {"grade": set(), "district": set()}; for response in raw_data: chosen_options["grade"].add(response["grade"]) chosen_options["district"].add(response["district"])
from opbeat.contrib.flask import Opbeat ''' Base directory of where the site is held ''' oec_dir = os.path.abspath(os.path.dirname(__file__)) # Initialize app app = Flask(__name__, template_folder=os.path.join(oec_dir, 'html')) app.wsgi_app = ProxyFix(app.wsgi_app) # Load default configuration from config.py app.config.from_object('config') cache_timeout = 604800 if DEBUG: from flask.ext.scss import Scss Scss(app) # override cache timeout cache_timeout = 0 from flask.ext.assets import Environment, Bundle assets = Environment(app) assets.load_path.append(os.path.join(oec_dir, "assets/js/")) js = Bundle("warning.js", "visualization.js", "configs/*.js", "helpers/*.js", output="js/visualization.js") assets.register("js", js) # DB connection object db = SQLAlchemy(app)
def __init__(self, config): tmp = config['hook']['tmp_path'], file_log = config['server']['file_log'] app = Flask(__name__) # git-deploy config to Flask config app.config['DEBUG'] = config['server']['debug'] app.config['SERVER_NAME'] = 'localhost:{}'.format( config['server']['port']) app.config['SQLALCHEMY_DATABASE_URI'] = config['server'][ 'database_uri'] app.config['SECRET_KEY'] = 'some_super_secret_random_key_' # app.config['SQLALCHEMY_ECHO'] = True # Init flask extensions db.init_app(app) Scss(app) with app.app_context(): db.create_all() db.session.commit() if not app.debug and file_log != None: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler(file_log) file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) # Filters @app.template_filter('cut_sha') def cut_sha_filter(sha): return sha[:6] @app.template_filter('datetime_add') def datetime_add_filter(date, secons_add): return date + datetime.timedelta(0, secons_add) @app.template_filter('format_since') def format_since_filter(date): now = datetime.datetime.now() since_seconds = int((now - date).total_seconds()) m, s = divmod(since_seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) mo, d = divmod(d, 30) # ~ number = 0 string = 'second' if mo: number = mo string = 'month' elif d: number = d string = 'day' elif h: number = h string = 'hour' elif m: number = m string = 'minute' elif s: number = s string = 'second' if number != 1: string += 's' return 'about {} {} ago'.format(number, string) @app.template_filter('format_seconds') def format_seconds_filter(seconds): m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) string = ['{} sec'] string_format = [s] if m: string.insert(0, '{} min') string_format.insert(0, m) if h: string.insert(0, '{} hour') string_format.insert(0, h) if d: string.insert(0, '{} day') string_format.insert(0, d) return ' '.join(string).format(*string_format) @app.template_filter('gravatar') def gravatar_filter(email, size=40): return 'https://www.gravatar.com/avatar/{}?s={}&d=retro'.format( hashlib.md5(email.lower()).hexdigest(), size) @app.template_filter('format_status') def format_status_filter(status): statuses = {} statuses['ERROR'] = 'failed' statuses['OK'] = 'passed' statuses['WARNING'] = 'passed with warnings' statuses['UNKNOWN'] = 'status is unknown' statuses['RUNNING'] = 'deploy is running' return statuses[status] # Pages @app.errorhandler(404) def not_found(error): #return jsonify({'message': str(error)}), 404 return render_template("404.html", message=str(error)), 404 @app.route('/<string:server>') def namespace_list(server): server = db.session.query(Server).filter( Server.name == server).first() return render_template("namespace.html", server=server) @app.route('/<string:server>/<string:namespace>') def project_list(server, namespace): namespace = db.session.query(Namespace).join(Repository).join( Server).filter(Server.name == server, Namespace.name == namespace).first() if namespace is None or namespace.repository is None: flash('No repositories found for this namespace', 'warning') return render_template("repository.html", namespace=namespace) @app.route('/', defaults={ 'server': None, 'namespace': None, 'repository': None, 'commit': None }, methods=['GET']) @app.route('/<string:server>/<string:namespace>/<string:repository>', defaults={'commit': None}, methods=['GET']) @app.route( '/<string:server>/<string:namespace>/<string:repository>/deploy/<string:commit>', methods=['GET']) def index(server, namespace, repository, commit): latest_commit_repository = db.session.query(Commit).join( Branch).join(Repository).join(Deploy).group_by( Repository.id).order_by(Commit.created.desc()) query_filter = [] if server and namespace and repository: query_filter.append(Server.name == server) query_filter.append(Namespace.name == namespace) query_filter.append(Repository.name == repository) if commit: query_filter.append(Commit.sha == commit) else: # Commit not set lets find last one and use that last_commit = db.session.query(Commit).join(Branch).join( Repository).join(Deploy).filter( *query_filter).order_by( Commit.created.desc()).first() if last_commit: query_filter.append(Commit.sha == last_commit.sha) else: # nothing set lest use latestcommit first_last_commit_repository = latest_commit_repository.first() query_filter.append(Server.id == first_last_commit_repository. branch.repository.namespace.server.id) query_filter.append( Namespace.id == first_last_commit_repository.branch. repository.namespace.id) query_filter.append( Repository.id == first_last_commit_repository.branch.repository.id) query_filter.append( Commit.id == first_last_commit_repository.id) result = db.session.query( Commit, func.sum(Deploy.runtime).label("total_runtime")).join( Branch).join(Repository).join(Deploy).filter( *query_filter).group_by(Repository.id).order_by( Commit.created.desc()).first() if result is None: abort(404) first_last_commit, total_runtime = result branches = db.session.query(Branch).join(Repository).join( Namespace).join(Server).filter( Server.id == first_last_commit.branch.repository.namespace.server.id, Namespace.id == first_last_commit.branch.repository.namespace.id, Repository.id == first_last_commit.branch.repository.id).order_by( Branch.updated.desc()) commits = db.session.query(Commit).join(Branch).join( Repository).join(Namespace).join(Server).filter( Server.id == first_last_commit.branch.repository.namespace.server.id, Namespace.id == first_last_commit.branch.repository.namespace.id, Repository.id == first_last_commit.branch.repository.id, Commit.id != first_last_commit.id).order_by( Commit.created.desc()) return render_template( "index.html", latest_commit_repository=latest_commit_repository, commit=first_last_commit, total_runtime=total_runtime, branches=branches, commits=commits) @app.route( "/<string:server>/<string:namespace>/<string:repository>.svg") def deploy_status(server, namespace, repository): found = db.session.query(Repository).join(Namespace).join( Server).filter(Server.name == server, Namespace.name == namespace, Repository.name == repository).first() found = db.session.query(Commit).join(Branch).join( Repository).join(Namespace).join(Server).filter( Server.name == server, Namespace.name == namespace, Repository.name == repository).order_by( Commit.created.desc()).first() my_path = os.path.dirname(os.path.realpath(__file__)) image = open( os.path.join( my_path, 'assets/images/{}.svg'.format( found.status.lower()))).read() return Response(image, mimetype='image/svg+xml') @app.route("/deploy.json", methods=['POST', 'GET']) def deploy(): if request.json == None: return jsonify({'message': 'I eat only JSON... bark, bark!'}), 400 try: git_deploy_remote.GitDeployRemote( request.json['after'], request.json['ref'], request.json['repository']['url'], tmp) return jsonify({'message': 'ok'}), 200 except Exception as e: return jsonify({'message': str(e)}), 500 app.run()
import os import supervise_web from supervise_web import core from supervise_web.app import app import mimetypes from supervise_web import helpers from flask.ext.scss import Scss import ConfigParser if __name__ == "__main__": app.debug = True package_root = os.path.dirname(supervise_web.__file__) Scss(app, asset_dir=os.path.join(package_root, 'assets'), static_dir=os.path.join(package_root, 'static/css')) app.jinja_env.globals['helpers'] = helpers mimetypes.add_type('application/x-font-woff', '.woff') core.config = ConfigParser.RawConfigParser() with open('supervise_web.cfg', 'r') as f: core.config.readfp(f) local = core.config.getboolean('Main', 'local') host = '127.0.0.1' if local else '0.0.0.0' port = core.config.getint('Main', 'port') app.run(host=host, port=port, debug=True)
if parser.has_option('webserver', 'static_url'): app.static_url_path = "//" + parser.get('webserver', 'static_url') assets.url = parser.get('webserver', 'static_url') if parser.getboolean('webserver', 'force_https'): try: from flask_sslify import SSLify sslify = SSLify(app, permanent=True) except ImportError: pass if parser.getboolean('application', 'debug'): app.debug = True Scss(app, static_dir='static/css', asset_dir='static/sass', load_paths=['static/sass']) app.secret_key = parser.get('application', 'secret_key') app.config['MAX_CONTENT_LENGTH'] = parser.get('webserver', 'uploadsize') * 1024 * 1024 APPLICATION_NAME = parser.get('application', 'name') client = MongoClient() db = client.pastedirectory def static_url_for(filename): if parser.has_option('webserver', 'static_url'): return parser.get('webserver', 'static_url') + "/" + filename else: return url_for('static', filename=filename)