I have been thinking of this, is there anyway to put my credential into
settings.py.
My generator.py is as following
import os
import sys
import collections
import boto
from boto.s3.key import Key
from flask import Flask, render_template, url_for, abort, request
from flask.ext.frozen import Freezer
from werkzeug import cached_property
from werkzeug.contrib.atom import AtomFeed
import markdown
import yaml
from string import strip
...
class Blog(object):
def __init__(self, app, root_dir='',file_ext=None):
self.root_dir = root_dir
self.file_ext = file_ext if file_ext is not None else app.config['POSTS_FILE_EXTENSION']
self._app =app #_ for private and internal
self._cache = SortedDict(key = lambda p: p.date, reverse= True)
self._initialize_cache()
...
app = Flask(__name__)
app.config.from_envvar('SETTINGS_FILE') #configuration file
blog = Blog(app, root_dir= 'posts')
freezer = Freezer(app)
DOMAIN = 'cuboid.example.net'
AWS_ACCESS_KEY_ID = 'ABCDEFGHIJK'
AWS_SECRET_ACCESS_KEY = 'HUIHUGERUGHIUHSIUHH'
currently I cant put the credential in it as the boto does not settings.py Can you tell me if there is a way to work AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY into settings.py?
Create a file called settings.py, place your keys inside of it, load it with import settings and then reference them as settings.AWS_ACCESS_KEY_ID.
However, from a security perspective you should really use IAM Roles instead. They automatically provide temporary keys to each EC2 instance.
http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-usingrole-ec2instance.html
Related
Hello everyone I have this issue I am not able to correct:
KeyError: 'A secret key is required to use CSRF.'
I am now using Flask with Blueprint.
I am not using CSRF at all but I think the LoginForm is.
I structured my project with Blueprint.
Before that, everything was find.
Here is my init.py file:
from flask import Flask
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.config import Config
from flask_wtf.csrf import CSRFProtect
db = SQLAlchemy()
migrate = Migrate(db)
bcrypt = Bcrypt()
csrf = CSRFProtect()
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.login_message_category = "info"
from Flask import models
from Flask.models import User
admin = Admin(name='Admin')
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
admin.init_app(app)
db.init_app(app)
csrf.init_app(app)
login_manager.init_app(app)
migrate.init_app(app)
bcrypt.init_app(app)
db.init_app(app)
from Flask.users.routes import users
app.register_blueprint(users)
return app
This is my config.py file:
import os
class Config:
SECRET_KEY = "ef2006629e09b70e55a6fb95c4e3a538"
SQLALCHEMY_DATABASE_URI = "sqlite:///site.db"
# WTF_CSRF_SECRET_KEY= "bjk567nvhbvj63vg363vghvghv3768vgfbkijvr784"
# CSRF_ENABLED = True
Thank you for your help !
You should create a SECRET_KEY=<Your secret key here> property in your configuration. It must be a difficult string.
I found the problem
I was not calling properly my config.py file
In my init.py file I change the line:
from flask.config import Config
with the line:
from Flask.config import Config
Flask is the name of my file, which is different from flask.
I should have found another name
How to add MySQL config to Flask app and create cursor and use in other classes?
I have 2 files:
app.py:
from flask import Flask
from flask_restful import Api
from Query import Query
from flask_mysqldb impoty MySQL
app= Flask(__name__)
api = Api(app)
api.add_resouce(Query,'/')
app.config['MYSQL_HOST'] = 'host'
#(same for user, password, db)
mysql = MySQL(app)
Query.py:
I am trying to import mysql FROM app.py so I can execute SQL on my DB.
from flask_restfull import Resource
from app import mysql
class Query(Resource):
def get(self):
pass
Error is caused by circular import. How to fix it?
"cannot import name 'Query'
Initialize mysql in another file, and reference it from both query.py and app.py. Inject it into the app using MySQL.init_app method
https://flask-mysqldb.readthedocs.io/en/latest/#flask_mysqldb.MySQL
# database.py
from flask_mysqldb import MySQL
mysql = MySQL()
# query.py
from database import mysql # <--!!!
from flask_restfull import Resource
class Query(Resource):
def get(self):
pass
# app.py
from flask import Flask
from flask_restful import Api
from database import mysql # <--!!!
from query import Query
app = Flask(__name__)
api = Api(app)
api.add_resouce(Query,'/')
app.config['MYSQL_HOST'] = 'host'
mysql.init_app(app) # <--!!!
The django app runs on the local server, but does not work on the remote.
The server does not have a GUI and does not provide the user with a link to authorization. The server outputs link to the console.
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import os
import json
SCOPES = 'https://www.googleapis.com/auth/calendar'
from .models import Aim
try:
import argparse
flags = tools.argparser.parse_args([])
except ImportError:
flags = None
def calendar_authorization(username):
store = open('app/static/secret_data/' + username +'.json', 'w')
store.close()
store = file.Storage('app/static/secret_data/' + username +'.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('app/client_secret.json', SCOPES)
flags.noauth_local_webserver = True
print("________flow_______")
print(flow.__dict__)
creds = tools.run_flow(flow, store, flags)
print("________creds_______")
print(creds.__dict__)
In the local version, I use client_secret.json, obtained from OAuth 2.0 client IDs. I suspect that I may have the wrong settings for this.
I found the information to use the Service account keys(I don't use it now). But I didn’t find a good setup guide for this.
How to set it up and paste in the code for authorization(
I did not understand how the access service key is used in the code?)?
What could be wrong?
I want to use flask-security.
I'm using a template flask app which creates global objects for extensions, and then initialises them when the app is created.
e.g. in extensions.py there is code like this:
from flask_bcrypt import Bcrypt
from flask_caching import Cache ...
from flask_security import Security ...
bcrypt = Bcrypt() ...
security = Security()
and then in app.py a call to register_extensions(app) which uses init_app(app) methods like so:
bcrypt.init_app(app)
security.init_app(app)
and indeed flask-security has an init_app() method. But the documentation says that the Security object needs a DataStore object which needs the User and Role model. It doesn't feel right to import the User and Role model in app.py when so far no other extension needs that.
What is the best practice for using Flask-Security when using the 'large Flask app' model ... I don't find the documentation helpful. It is a simple case when all objects are defined in one place.
Below is what I have.
extensions.py
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security
db = SQLAlchemy()
security = Security()
__init__.py
from .extensions import db, security
from .models import User, Role
def create_app(config_name):
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security.init_app(app, user_datastore)
I am trying to use a custom Baseconverter to ensure that my urls are "clean". I finally got it to work as follows:
My init.py is:
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import basedir
from slugify import slugify
app = Flask(__name__)
from werkzeug.routing import BaseConverter
class MyStringConverter(BaseConverter):
def to_python(self, value):
return value
def to_url(self, values):
return slugify(values)
app.url_map.converters['mystring'] = MyStringConverter
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
oid = OpenID(app, os.path.join(basedir, 'tmp'))
from app import views, models
But if I define the MyStringConverter class and add app.url_map.converters['mystring'] = MyStringConverter at the end of the file instead, I got a LookupError: the converter 'mystring' does not exist error. Why is this?
Is this the correct way to clean up my urls? I'm not sure if I need to do anything to the to_python() method or if I am going about this the right way.