def init_app(app): # We load configurations first from the config file (where some options # are overridable via environment variables) or from the config file # pointed to by the MEASUREMENTS_CONFIG environment variable. # The later overrides the former. app.config.from_object('measurements.config') app.config.from_envvar('MEASUREMENTS_CONFIG', silent=True) app.logger.addHandler(logging.StreamHandler()) if app.config['APP_ENV'] == 'production': app.logger.setLevel(logging.WARNING) elif app.config['APP_ENV'] == 'development': app.logger.setLevel(logging.DEBUG) # Set the jinja templates to reload when in development if app.config['APP_ENV'] == 'development': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True for key in app.config.keys(): # Do not log, even in debug, anything containing the work "SECRET" if "SECRET" in key: continue app.logger.debug("{}: {}".format(key, app.config[key])) md = Misaka(fenced_code=True) md.init_app(app) CORS(app, resources={r"/api/*": {"origins": "*"}}) cache.init_app(app, config=app.config['CACHE_CONFIG'])
def add_extensions(application): global db global mail_app global md global md_no_mj global logger global mb global socketio # App.testing indicates that the database is sqlite://:memory: if not app.testing: application.config[ 'SQLALCHEMY_DATABASE_URI'] += "_debug" if application.debug else "_prod" db = SQLAlchemy(application) mail_app = Mail(application) md = Misaka(application, **application.config['MISAKA_CONFIG']) md_no_mj = Misaka( application, **{ **application.config['MISAKA_CONFIG'], "math": False, "math_explicit": False }) mb = Mobility(app) logger = application.logger socketio = SocketIO(app)
def init_app(app): # We load configurations first from the config file (where some options # are overridable via environment variables) or from the config file # pointed to by the MEASUREMENTS_CONFIG environment variable. # The later overrides the former. app.config.from_object('measurements.config') app.config.from_envvar('MEASUREMENTS_CONFIG', silent=True) app.logger.addHandler(logging.StreamHandler()) if app.config['APP_ENV'] == 'production': app.logger.setLevel(logging.WARNING) elif app.config['APP_ENV'] == 'development': app.logger.setLevel(logging.DEBUG) # Set the jinja templates to reload when in development app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['DEBUG'] = True elif app.config['APP_ENV'] not in ( 'testing', 'staging'): # known envs according to Readme.md raise RuntimeError('Unexpected APP_ENV', app.config['APP_ENV']) for key in app.config.keys(): SECRET_SUBSTRINGS = ["_SECRET_", "DATABASE_URL"] # Do not log, even in debug, anything containing the word "SECRET" or "DATABASE_URL" if any([s in key for s in SECRET_SUBSTRINGS]): continue app.logger.debug("{}: {}".format(key, app.config[key])) md = Misaka(fenced_code=True) md.init_app(app) CORS(app, resources={r"/api/*": {"origins": "*"}})
def create_app(config_class=Config): app = Flask(__name__) from flaskblog.users.routes import users from flaskblog.posts.routes import posts from flaskblog.main.routes import main from flaskblog.categories.routes import categories from flaskblog.errors.handlers import errors app.config.from_object(Config) app.register_blueprint(users) app.register_blueprint(posts) app.register_blueprint(main) app.register_blueprint(errors) app.register_blueprint(categories) db.init_app(app) with app.app_context(): db.create_all() bcrypt.init_app(app) login_manager.init_app(app) md = Misaka(footnotes=True, tables=True) md.init_app(app) return app
def test_smartypants(self, html): text = "Don't call me Shirley" expected_result = "<p>Don’t call me Shirley</p>\n" md = Misaka(smartypants=True) result = md.render(text) self.assertIsInstance(result, Markup) self.assertEqual(result, expected_result)
def test_override_defaults(self, html): ext, flags = 0, 0 md = Misaka(autolink=True) result = md.render(TEST_MD, autolink=False) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_override_defaults(self, html): ext, flags = 0, 0 md = Misaka(autolink=True) result = md.render(TEST_MD, autolink=False) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_set_defaults(self, html): ext, flags = EXT_TABLES, HTML_HARD_WRAP md = Misaka(hard_wrap=True, tables=True) result = md.render(TEST_MD) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual( result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_set_defaults(self, html): ext, flags = EXT_TABLES, HTML_HARD_WRAP md = Misaka(hard_wrap=True, tables=True) result = md.render(TEST_MD) html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags) self.assertIsInstance(result, Markup) self.assertEqual(result, misaka.html(TEST_MD, extensions=ext, render_flags=flags))
def test_smartypants(self, html): text = "Don't call me Shirley" pantsed = "Don’t call me Shirley" expected_result = "<p>Don’t call me Shirley</p>\n" md = Misaka(smartypants=True) result = md.render(text) html.assert_called_with(pantsed, extensions=0, render_flags=0) self.assertIsInstance(result, Markup) self.assertEqual(result, expected_result)
def test_custom_renderer(self, html): class CustomRenderer(misaka.HtmlRenderer): def image(self, link, title, alt_text): return '<div><img src="{0}" alt="{2}" title="{1}"><div>{1}</div></div>'.format( link, title, alt_text) test_md = '![Alt text](/img.jpg "Title")' expected_result = '<p><div><img src="/img.jpg" alt="Alt text" title="Title"><div>Title</div></div></p>\n' md = Misaka(None, CustomRenderer()) result = md.render(test_md) self.assertFalse(html.called) self.assertEqual(str(result), expected_result)
def init_app(app, testmode=False): # We load configurations first from the config file (where some options # are overridable via environment variables) or from the config file # pointed to by the MEASUREMENTS_CONFIG environment variable. # The later overrides the former. app.config.from_object("measurements.config") app.config.from_envvar("MEASUREMENTS_CONFIG", silent=True) # Prevent messy duplicate logs during testing if not testmode: app.logger.addHandler(logging.StreamHandler()) if app.config["APP_ENV"] == "production": app.logger.setLevel(logging.WARNING) elif app.config["APP_ENV"] == "development": app.logger.setLevel(logging.DEBUG) # Set the jinja templates to reload when in development app.jinja_env.auto_reload = True app.config["TEMPLATES_AUTO_RELOAD"] = True app.config["DEBUG"] = True elif app.config["APP_ENV"] not in ( "testing", "staging", ): # known envs according to Readme.md raise RuntimeError("Unexpected APP_ENV", app.config["APP_ENV"]) for key in app.config.keys(): SECRET_SUBSTRINGS = ["_SECRET_", "DATABASE_URL"] # Do not log, even in debug, anything containing the word "SECRET" or "DATABASE_URL" if any([s in key for s in SECRET_SUBSTRINGS]): continue app.logger.debug("{}: {}".format(key, app.config[key])) if app.config["APP_ENV"] == "production": sentry_sdk.init( dsn="https://[email protected]/1367288", integrations=[FlaskIntegration()], ) # TODO Temporary workaround to ignore flask-limiter logs due to: # https://github.com/ooni/api/issues/145 & # https://github.com/alisaifee/flask-limiter/issues/186 ignore_logger("flask-limiter") md = Misaka(fenced_code=True) md.init_app(app) CORS(app, resources={r"/api/*": {"origins": "*"}})
def init_app(): from .config import (PORTAL_NON_ROOT, SECRET_KEY, DEBUG, LAB_NAME, RESIZE_URL, IMAGES_PATH, MAX_UPLOAD_SIZE, YANDEX_METRIKA, VK_ENABLE, JOBS_ENABLE, CGRDB_ENABLE, VIEW_ENABLE) from .logins import load_user app = Flask(__name__) app.config['DEBUG'] = DEBUG app.config['SECRET_KEY'] = SECRET_KEY app.config['ERROR_404_HELP'] = False login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = '.login' login_manager.user_loader(load_user) app_url = PurePosixPath('/') / (PORTAL_NON_ROOT or '') if VIEW_ENABLE: from flask_bootstrap import Bootstrap from flask_misaka import Misaka from flask_nav import Nav, register_renderer from flask_resize import Resize from misaka import HTML_ESCAPE from .views import view_bp from .views.bootstrap import top_nav, CustomBootstrapRenderer, CustomMisakaRenderer app.config['BOOTSTRAP_SERVE_LOCAL'] = DEBUG app.config['RESIZE_URL'] = RESIZE_URL app.config['RESIZE_ROOT'] = IMAGES_PATH app.config['MAX_CONTENT_LENGTH'] = MAX_UPLOAD_SIZE app.jinja_env.globals.update(year=datetime.utcnow, laboratory=LAB_NAME, yandex=YANDEX_METRIKA) Resize(app) register_renderer(app, 'myrenderer', CustomBootstrapRenderer) nav = Nav(app) nav.register_element('top_nav', top_nav) Bootstrap(app) Misaka(app, renderer=CustomMisakaRenderer(flags=0 | HTML_ESCAPE), tables=True, autolink=True, underline=True, math=True, strikethrough=True, superscript=True, footnotes=True) app.register_blueprint(view_bp, url_prefix=app_url.as_posix() if PORTAL_NON_ROOT else None) if JOBS_ENABLE: from .API import load_jobs app.register_blueprint(load_jobs(), url_prefix=(app_url / 'api' / 'jobs').as_posix()) if CGRDB_ENABLE: from .API import load_cgrdb app.register_blueprint(load_cgrdb(), url_prefix=(app_url / 'api' / 'db').as_posix()) if VK_ENABLE: from .vk import vk_bp app.register_blueprint(vk_bp, url_prefix=(app_url / 'api' / 'vk').as_posix()) return app
def create_app(config_class=Config): md = Misaka(tables=True, hard_wrap=True) app = Flask(__name__) md.init_app(app) app.config.from_object(Config) db.init_app(app) bcrypt.init_app(app) login_manager.init_app(app) mail.init_app(app) from flasksite.errors.handlers import errors from flasksite.users.routes import users from flasksite.posts.routes import posts from flasksite.main.routes import main app.register_blueprint(errors) app.register_blueprint(users) app.register_blueprint(posts) app.register_blueprint(main) return app
def register_filters(app): Misaka(app, autolink=True, fenced_code=True, strikethrough=True) @app.template_filter() def since_date(value): return timesince(value) @app.template_filter() def until_date(value): return timesince(value, default="now!", until=True) @app.template_filter() def format_date(value, format='%Y-%m-%d'): return value.strftime(format)
def create_app(configfile=None): # We are using the "Application Factory"-pattern here, which is described # in detail inside the Flask docs: # http://flask.pocoo.org/docs/patterns/appfactories/ app = Flask(__name__, static_url_path='') # We use Flask-Appconfig here, but this is not a requirement AppConfig(app, configfile) # Kludges for heroku if 'DYNO' in os.environ: # HerokuConfig is only needed if you do smtp etc. but whatever. from flask_appconfig import HerokuConfig HerokuConfig(app) from flask_sslify import SSLify sslify = SSLify(app, permanent=True) app.config['PREFERRED_URL_SCHEME'] = 'https' stdout_logging(app) app.config['DATABASE'] = os.environ.get('DATABASE_URL') database.init_app(app) BabelByUrl(app) ## Note: if you remove roles, they *don't* get removed from # an existing datastore (flask_security doens't support that), # If you *really* need this, start from a fresh db. # USER_ROLES are hardwired in code, because without code changes # they're meaningless ;) # Also note that you don't need to explicitly mention 'admin'. app.config['USER_ROLES'] = ['editor'] init_auth(app) init_models(app) app.config['BOOTSTRAP_SERVE_LOCAL'] = True # CDNs are cancer Bootstrap(app) Misaka(app) init_custom_nav_renderer(app) nav.init_app(app) app.register_blueprint(frontend, template_folder='templates') app.register_blueprint(backend, url_prefix='/editors') app.register_blueprint(useradmin, url_prefix='/useradmin', template_folder='sitepack/templates') return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config['default']) app.config.from_object(config[config_name]) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # app.config['SQLALCHEMY_ECHO'] = True app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False app.config['SIMPLEMDE_USE_CDN'] = True app.config['SIMPLEMDE_JS_IIFE'] = True # ------ APPLICATION FACTORY ----- # db.init_app(app) migrate.init_app(app, db) bootstrap.init_app(app) toolbar.init_app(app) login_manager.init_app(app) simplemde.init_app(app) moment.init_app(app) csrf.init_app(app) Misaka(app, fenced_code=True, strikethrough=True, tables=True, highlight=True, autolink=True, no_intra_emphasis=True, underline=True, smartypants=True, qoute=True) from app.models import Entries # import local for whoosh index wa.whoosh_index(app, Entries) # ------- BLUEPRINTS --------------# from .blog import blog as blog app.register_blueprint(blog) ''' Blueprint was required after making the application factory. As the app instance is created and configured at run time and thus the 'app' has already created, you cannot access the 'app' after this. I.e. the app in app.route is inaccessible: blueprints mitigate this. ''' return app
def edusign_init_app(name: str, config: Optional[dict] = None) -> EduSignApp: """ Create an instance of an edusign data app. :param name: Name for the Flask app :param config: To update the config, mainly used in tests :return: The Flask app. """ app = EduSignApp(name) CORS(app, origins=[]) Misaka(app) app.config.from_object('edusign_webapp.config') if config is not None: app.config.update(config) app.api_client = APIClient(app.config) app.babel = Babel(app) app.doc_store = DocStore(app) app.mailer = Mail(app) from edusign_webapp.views import anon_edusign_views, edusign_views app.register_blueprint(anon_edusign_views) app.register_blueprint(edusign_views) to_tear_down = app.config['TO_TEAR_DOWN_WITH_APP_CONTEXT'] for func_path in to_tear_down: module_path, func_name = func_path.rsplit('.', 1) func = getattr(import_module(module_path), func_name) app.teardown_appcontext(func) app.logger.info(f'Init {name} app...') return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) db.init_app(app) pagedown.init_app(app) moment.init_app(app) mail.init_app(app) login_manager.init_app(app) Misaka(app) from .site import site as site_blueprint app.register_blueprint(site_blueprint) from .blog import blog as blog_blueprint app.register_blueprint(blog_blueprint, url_prefix='/blog') from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
def register_filters(app): # Library filters Misaka(app, autolink=True, fenced_code=True, strikethrough=True, tables=True) # Registration of handlers for micawber app.oembed_providers = bootstrap_basic() @app.template_filter() def onebox(value): return make_oembedplus(value, app.oembed_providers, maxwidth=600, maxheight=400) # Custom filterss @app.template_filter() def since_date(value): return timesince(value) @app.template_filter() def until_date(value): return timesince(value, default="now!", until=True) @app.template_filter() def format_date(value, format='%d.%m.%Y'): return value.strftime(format) @app.template_filter() def format_datetime(value, format='%d.%m.%Y %H:%M'): return value.strftime(format)
from flask_sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap from flask_marshmallow import Marshmallow from flask_misaka import Misaka from flask_security import Security, SQLAlchemyUserDatastore from flask_bootstrap import StaticCDN # Init bootstrap extension bootstrap = Bootstrap() # Init SQL extension db = SQLAlchemy() ma = Marshmallow() # Init other extensions misaka = Misaka() security = Security() # Init user management from .models.user import User, Role user_datastore = SQLAlchemyUserDatastore(db, User, Role) def create_app(config_filename): app = Flask(__name__) app.config.from_object(config_filename) app.logger.setLevel(app.config["LOG_LEVEL"]) bootstrap.init_app(app) app.extensions['bootstrap']['cdns']['jquery'] = StaticCDN()
def test_init(self): md = Misaka() app2 = Flask(__name__) md.init_app(app2) self.assertIn("markdown", app2.jinja_env.filters)
def test_smartypants_table(self, html): "smartypants should not interfere with processing tables" text = dedent(""" | Left align | Right align | Center align | |:-----------|------------:|:------------:| | This | This | This | | column | column | column | | will | will | will | | be | be | be | | left | right | center | | aligned | aligned | aligned | """) expected_result = dedent(""" <table> <thead> <tr> <th style="text-align: left">Left align</th> <th style="text-align: right">Right align</th> <th style="text-align: center">Center align</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">This</td> <td style="text-align: right">This</td> <td style="text-align: center">This</td> </tr> <tr> <td style="text-align: left">column</td> <td style="text-align: right">column</td> <td style="text-align: center">column</td> </tr> <tr> <td style="text-align: left">will</td> <td style="text-align: right">will</td> <td style="text-align: center">will</td> </tr> <tr> <td style="text-align: left">be</td> <td style="text-align: right">be</td> <td style="text-align: center">be</td> </tr> <tr> <td style="text-align: left">left</td> <td style="text-align: right">right</td> <td style="text-align: center">center</td> </tr> <tr> <td style="text-align: left">aligned</td> <td style="text-align: right">aligned</td> <td style="text-align: center">aligned</td> </tr> </tbody> </table> """) md = Misaka(tables=True, smartypants=True) result = md.render(text).strip() self.assertIsInstance(result, Markup) self.assertEqual(result.strip(), expected_result.strip())
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_moment import Moment from flask_login import LoginManager from flask_misaka import Misaka from config.application import DevelopmentConfig app = Flask(__name__, static_folder='assets', template_folder='views') app.config.from_object(DevelopmentConfig) db = SQLAlchemy(app) migrate = Migrate(app, db) moment = Moment(app) login = LoginManager(app) login.login_view = 'auth.login' Misaka(app, no_intra_emphasis=True, escape=True, autolink=True, math=True) from app.controllers import routes from app.controllers import scheduler from app.controllers import error_controller from app.helper import template_tags
def create_app(config="app.config"): app = Flask(__name__) with app.app_context(): app.config.from_object(config) app.jinja_loader = BlogthemeLoader(os.path.join( app.root_path, app.template_folder), followlinks=True) from app.models import db, Users url = make_url(app.config['SQLALCHEMY_DATABASE_URI']) if url.drivername == 'postgres': url.drivername = 'postgresql' db.init_app(app) try: if not (url.drivername.startswith('sqlite') or database_exists(url)): create_database(url) db.create_all() except OperationalError: db.create_all() else: db.create_all() app.db = db cache.init_app(app) app.cache = cache app.debug = False configure_uploads(app, photos) redis_store = FlaskRedis() redis_store.init_app(app) login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.oauth' login_manager.init_app(app) toolbar = DebugToolbarExtension(app) #toolbar.DEBUG_TB_INTERCEPT_REDIRECTS = False md = Misaka() md.init_app(app) Analytics(app) app.config['ANALYTICS']['GAUGES']['SITE_ID'] = 'XXXXXXXXXXXXX' if not get_config('blog_theme'): set_config('blog_theme', 'blog') from app.views import views from app.utils import init_errors, init_utils, init_logs from app.post import blog from app.auth import auth from app.admin import admin from app.status import web #from app.api import init_errors(app) init_utils(app) init_logs(app) app.register_blueprint(views) app.register_blueprint(blog) app.register_blueprint(auth) app.register_blueprint(admin) app.register_blueprint(web) @login_manager.user_loader def load_user(user_id): try: return Users.query.get(int(user_id)) except Users.DoesNotExist: return None return app
from methods import comment_history, recreate_body_diffs, parse_identifier app = Flask(__name__) app.config[ 'MONGO_URI'] = 'mongodb://*****:*****@mongo1.steemdata.com:27017/SteemData' mongo = PyMongo(app) # enable markdown rendering md_features = [ 'autolink', 'fenced_code', 'underline', 'highlight', 'quote', 'math', 'superscript', 'tables', 'wrap' ] md_features = {x: True for x in md_features} Misaka(app, **md_features) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/history', methods=['GET']) def history(): identifier_uri = request.args.get('identifier') app.logger.info(identifier_uri) comments = comment_history(mongo.db, identifier_uri) if not comments: abort(404) original, diffs = recreate_body_diffs(comments)
db = SQLAlchemy(app) # password hashing bcrypt = Bcrypt(app) # email mail = Mail(app) # login login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "users.login" # Markdpwn Editor SimpleMDE(app) md = Misaka(fenced_code=True, tables=True) md.init_app(app) # Chat # socketio = SocketIO() # socketio.init_app(app) from app.models import User @login_manager.user_loader def load_user(user_id): return User.query.filter(User.id == int(user_id)).first() # blueprints
from timeslot_chart import * from read_db import filt_shows # Demo form import numpy as np #import xgboost as xgb import pickle content = "" with open("./data/ML_Analysis.md", "r") as f: content = f.read() app = Flask(__name__) app.config['SECRET_KEY'] = 'iridescent' bootstrap = Bootstrap(app) Misaka(app) # To use markdown in the template @app.route('/Analytics') def analytics(): contents = content contents = Markup(markdown.markdown(contents)) return render_template('home.html', content=contents) #return render_template('ML_Analysis.html') @app.route('/for_orgcode_charts_json') def for_orgcode_charts(feature='OrgCode'): show_df, noshow_df = filt_shows() show_labels = [0] * len(show_df.index) + [1] * len(noshow_df.index) info = pd.concat([show_df, noshow_df], axis=0)
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_cache import Cache from flask_bootstrap import Bootstrap from flask_misaka import Misaka from flask_mail import Mail # 数据库实例 db = SQLAlchemy() # redis 缓存 cache = Cache() # bootstrap实例 bootstrap = Bootstrap() # markdown md = Misaka() # 发送邮件 mail = Mail() # 登录配置 login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login'
__author__ = 'Jeremy Van' # set up Flask App app = Flask(__name__, instance_relative_config=True) # Enable CSRF protection globally for Flask app csrf = CSRFProtect(app) csrf.init_app(app) app.config.from_pyfile('portal.conf') app.url_map.strict_slashes = False app.config['DEBUG'] = True app.permanent_session_lifetime = timedelta(minutes=1440) app.config.update(SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax') # set up Markdown Rendering md = Misaka() md.__init__(app, tables=True, autolink=True, fenced_code=True, smartypants=True, quote=True, math=True, math_explicit=True) # set up logging handler = logging.handlers.RotatingFileHandler( filename=app.config['SLATE_WEBSITE_LOGFILE']) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
import sys import os import random import markdown from flask import Flask, render_template, jsonify, Markup, send_file from flask_misaka import Misaka app = Flask(__name__) Misaka(app, tables=True, autolink=True, wrap=True) md_dir = "Stories/" @app.route('/') def index(): return render_template('index.html') @app.route('/map') def map(): return render_template('map.html') @app.route('/blog') def blog(): content = get_file('our_autism_story.md') content = Markup(markdown.markdown(content)) return render_template('blog.html', content=content) @app.route('/grants') def grants():
import psycopg2 import psycopg2.extras import pg2geojson from flask_misaka import Misaka from werkzeug.urls import url_unquote_plus from datetime import datetime, timedelta from jinja2 import ChoiceLoader, FileSystemLoader from flask import Flask, render_template, request, make_response, url_for, send_from_directory from flask_cors import CORS import logging from logging import StreamHandler # Define the Flask app and add support for Markdown in templates app = Flask(__name__) md = Misaka(tables=True, autolink=True, toc=True) md.init_app(app) # Exposes all resources matching /developmentcontrol/* to CORS CORS(app, resources=r'/developmentcontrol/*', allowed_headers=['Content-Type', 'X-Requested-With']) # Configure logging to stderr log_handler = StreamHandler() log_handler.setLevel(logging.INFO) app.logger.addHandler(log_handler) # Add the to the template search path so that we can treat our built hubmap.js # as a template without having to manually copy it to the standard template # directory DIST_DIR = os.path.join(app.static_folder, 'hubmap/dist') template_loader = ChoiceLoader([
redirect, render_template, request, session, url_for) from flask_login import current_user, login_required, login_user, logout_user from flask_misaka import Misaka from flask_session import Session from forms import ChangePasswordForm, CreateNoteForm, LoginForm, RegisterForm from login import login_manager from models import Login, Note, Share, User, db, initial_input from password_strength import PasswordPolicy, PasswordStats from flask_wtf.csrf import CSRFError ################################ #configuracja app = Flask(__name__) app.config.from_object(Config) Session(app) Misaka(app, escape=True) db.init_app(app) with app.app_context(): db.drop_all() db.create_all() db.session.commit() initial_input() login_manager.init_app(app) policy = PasswordPolicy.from_names( length=8, # minimalna dlugosc: 8 uppercase=2, # minimum 2 wielkie litery numbers=2, # minimum 2 cyfry special=2, # minimum 2 specialne znaki )
hops = port.split(',') if os.environ.get('JUPYTERHUB_USER') and len(hops) > 1: environ['SERVER_PORT'] = hops[-2] else: environ['SERVER_PORT'] = hops[-1] return app(environ, start_response) return _app app.wsgi_app = proxy_fix(app.wsgi_app) # Setup markdown filter for formatting. mikasa = Misaka(app, fenced_code=True) # Setup asciidoc filter for formatting. def asciidoc(value): output = value asciidoc = AsciiDocAPI() asciidoc.options('--no-header-footer') result = StringIO.StringIO() asciidoc.execute(StringIO.StringIO(output.encode('utf-8')), result, backend='html5') return unicode(result.getvalue(), "utf-8")
#!/usr/bin/env python2.7 import sys import urllib2 import glob import random import os import subprocess import threading import json from flask_misaka import Misaka from flask import Flask, render_template, request, jsonify, escape # Web Application Variables app = Flask(__name__, static_url_path='', static_folder='web/static', template_folder='web/templates') Misaka(app) # Set Progress file to False with open("files/finished/aquatone.txt", "w+") as progress_checker: progress_checker.write("false") with open("files/finished/port-scanning.txt", "w+") as progress_checker: progress_checker.write("false") with open("files/finished/ssl-scanning.txt", "w+") as progress_checker: progress_checker.write("false") with open("files/api_keys.json", 'r') as api_keys: aquatone_key_types = [ "shodan", "censys_id", "censys_secret",
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy import os from flask.ext.login import LoginManager from flask.ext.openid import OpenID from flask.ext.admin import Admin from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD from flask_misaka import Misaka from app.renderers import QuilltRenderer app = Flask(__name__) app.config.from_object('config') Bootstrap(app) db = SQLAlchemy(app) m = Misaka(app, QuilltRenderer()) print(m.render("This is a test (r) [[test]]")) #lm = LoginManager() #lm.init_app(app) #lm.login_view = 'login' #oid = OpenID(app, os.path.join(basedir, 'tmp')) if not app.debug: import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT),