#Tells sqlAlchemy where to find the data.db file app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' #Its sort of a listener # In order to know when an object changes, but not changed in the database # extension flask_sqlalchemy was tracking it. However we dont need it because # SQLAlchemy already has a tracker built into its library app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #JWT: Will create a new endpoint #we send JWT a user name and a password #then it will call the authenticate method #if authentication is good, a JWT token will be sent back and stored in jwt #JWT will only use the identity_function when it sends a JWT token jwt = JWT(app, authenticate, identity) # /auth, /login after 'JWT_AUTH_URL_RULE' @jwt.auth_response_handler def customized_response_handler(access_token, identity): return jsonify({ 'authorization' : access_token.decode('utf-8'), 'user_id': identity.id }) api.add_resource(Store, '/store/<string:name>') api.add_resource(StoreList, '/stores') #add_resource: adds a resource to the API api.add_resource(Item, '/item/<string:name>') # http://127.0.0.1/student/Edwin
db_module = __import__('20191209_db') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:/Users/nldomme8/Documents/data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'joost' # long and complicated api = Api(app) @app.before_first_request def create_tables(): db_module.db.create_all() jwt = JWT(app, sec.authenticate, sec.identify) # /auth api.add_resource(store_mod.Store, '/store/<string:name>') api.add_resource(item_mod.Item, '/item/<string:name>') api.add_resource(item_mod.ItemList, '/items') api.add_resource(store_mod.StoreList, '/stores') api.add_resource(user_mod.UserRegister, '/register') if __name__ == '__main__': db_module.db.init_app(app) app.run(port=5000)
from resources.item import Item, ItemList from resources.store import Store, StoreList from resources.user import UserRegister app = Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'brayo123' # used to encode cookies api = Api(app) jwt = JWT(app, authenticate, identity) # /auth --> endpoint api.add_resource(Store, '/store/<string:name>') api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register') # api.add_resource(Store, '/store_append') @app.errorhandler( JWTError ) # helps to hold exceptions so that no info is passed to the clients/users def auth_error_handler(err): return jsonify({ 'message':
import os from flask import Flask, request from flask_restful import Resource, Api, reqparse from flask_jwt import JWT, jwt_required from security import authenticate, identity from resources.user import UserRegister from resources.task import Task, Task_list app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'DATABASE_URL', 'sqlite:///data.db') # data.db resides at root directory of project #app.config['PROPAGATE_EXCEPTIONS'] = True app.secret_key = 'sangram' api = Api(app) jwt = JWT(app, authenticate, identity) # creates a new endpoint /auth api.add_resource(Task, '/Task/<string:name>') api.add_resource(Task_list, '/Task_list') api.add_resource(UserRegister, '/User') if __name__ == '__main__': from db import db db.init_app(app) app.run(port=5000, debug=True)
from flask import Flask, request, render_template from flask_restful import Resource, Api from security import authentication, identity from flask_jwt import JWT, jwt_required app = Flask(__name__) app.secret_key = 'rose' api = Api(app) jwt = JWT(app, authentication, identity) items = [] class Item(Resource): @jwt_required() def get(self, name): item = next(filter(lambda x: x['name'] == name, items), None) return {'item': item}, 200 if item else 404 def post(self, name): if next(filter(lambda x: x['name'] == name, items), None) is not None: return { 'message': "An item with name {} already exists.".format(name) }, 400 data = request.get_json() item = {'name': name, 'price': data['price']} items.append(item) return item, 201
from flask import Flask, request from flask_restful import Resource, Api, reqparse from flask_jwt import JWT, jwt_required from security import authenticate, identify app = Flask(__name__) app.secret_key = 'didier' api = Api(app) jwt = JWT(app, authenticate, identify) # create endpoint: /auth # im this section we create a local database, next we'll conect to a database. items = [] class Item(Resource): # make sure to only some data in payload can be change. parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help="This cannot be left blank!") @jwt_required() def get(self, name): # return item if match the name or None if doesen't. item = next(filter(lambda x: x['name'] == name, items), None) return {'item': item}, 200 if item else 404 def post(self, name):
from security import authenticate, identity from resources.user import UserRegister from resources.item import Item, ItemList from resources.store import Store, StoreList from db import db app = Flask(__name__) app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' #doesn't have to be sqlite, can be MySQL, postgre, oracle app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'jose' api = Api(app) @app.before_first_request def create_tables(): db.create_all() jwt = JWT(app, authenticate, identity) #/auth endpoint created api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(Store, '/store/<string:name>') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register') if __name__ == '__main__': db.init_app(app) app.run(port=5000, debug=True)
from security import authenticate, identity from resources.user import UserRegister from resources.item import Item, ItemList from resources.store import Store, StoreList app = Flask(__name__) #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'jose' api = Api(app) #@app.before_first_request #def create_tables(): # db.create_all() jwt = JWT(app, authenticate, identity) #/auth #added new endpoint api.add_resource(Store, '/store/<string:name>') api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register') if __name__ == "__main__": from db import db db.init_app(app) app.run(port=5000, debug=True)
from flask import Flask from flask_restful import Api from flask_jwt import JWT from flask_cors import CORS from auth.security import authinticate, identity from resources.student import StudentResource app = Flask(__name__) app.secret_key = '$%^uke45f78v4ei#$%^&ydfg12734vgn35y65o2!@#$&^' CORS(app) api = Api(app) jwt = JWT(app, authinticate, identity) api.add_resource(StudentResource, '/students/', '/students/<int:student_id>/') if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
print(login_us) if corret_usr is not None: session['username'] = request.form.get('username') return render_template('index.html') return render_template('login.html') @app.route('/register/', methods=['GET', 'POST']) def register(): """Register Form""" if request.method == 'POST': print(request.form.get('username')) corrent_us = mongo.db.user.find_one({'uname': request.form.get('username').encode('utf-8')}) print(corrent_us) if corrent_us is None: username = request.form.get('username').encode('utf-8') password = request.form.get('password').encode('utf-8') haspws = bcrypt.hashpw(password,bcrypt.gensalt()) data = mongo.db.user.insert_one({'uname': username, 'psw': haspws}) session['username'] = request.form.get('username') return redirect(url_for('login')) return 'This user is already exists!' return render_template('register.html') if __name__ == '__main__': app.secret_key = 'secretkey' jwt = JWT(app, authenticate) app.run(host='127.0.0.1', port=5000, debug=True)
def authenticate(username, password): user = username_table.get(username, None) if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user def identity(payload): user_id = payload['identity'] return userid_table.get(user_id, None) application = Flask(__name__) application.config['SECRET_KEY'] = 'super-secret' jwt = JWT(application, authenticate, identity) @application.route('/') def index(): return 'Welcome in Youtube transcript api!' @application.route('/transcript/<movie_id>', methods=['GET']) @jwt_required() def transcript(movie_id: str): data = YouTubeTranscriptApi.get_transcript(movie_id) return jsonify(data)
from flask import Flask from flask_restful import Api, Resource from flask_jwt import JWT from security import authenticateuser, identity from Resources.users import modifyusers from Resources.items import Item, postItem from Resources.stores import Stores, AddStore from db import db app = Flask(__name__) #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///thisismydb.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@localhost/storenew' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False api = Api(app) app.secret_key = "london" jwt = JWT(app, authenticateuser, identity) class Items(Resource): def get(self): print("I am in get all items") return None api.add_resource(Items, '/items') api.add_resource(Item, '/item/<int:itemid>') api.add_resource(postItem, '/item') api.add_resource(modifyusers, '/users') api.add_resource(Stores, '/store/<int:storeId>') api.add_resource(AddStore, '/store')
import os # to access our postgres db environment variables from flask import Flask from flask_restful import Api from flask_jwt import JWT from security import authenticate, identity from resources.user import UserRegister from resources.item import Item, ItemList from resources.store import Store, StoreList app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db') #ONLINE/OFFLINE DB ACCESS ARGUEMENTS app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # turns off flask_sqlalchemy tracker as SQLAlchemy has a better one built in app.secret_key = 'aSecretKey' api = Api(app) jwt = JWT(app, authenticate, identity) # creates a new endpiont.. /auth api.add_resource(Store, '/store/<string:name>') api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register')# this Resource is imported from user.py and added to the api here w/an endpoint if __name__ == '__main__':# this keeps app.py from running if we import it to another file and that file is read from db import db # imported here due to 'circular imports' db.init_app(app) app.run(port=5000, debug=True)
as a decorator as @jwt_required(), which will not allow the user to pass perform the operation unless verified ''' ''' It has to be there before we initialise the jwt ==> To change the by default url of /auth to something else, like /login, do this => app.config['JWT_AUTH_URL_RULE'] = '/login' ==> config JWT to expire within half an hour app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=1800) ==> config JWT auth key name to be 'email' instead of default 'username' app.config['JWT_AUTH_USERNAME_KEY'] = 'email' ''' jwt = JWT(app, authenticate, identity) # /auth is the url which JWT provides # items = [] # This adds the Resource to the api Class # and route will be mentioned here only # It helps in saving time for doing @app.route(URL) api.add_resource(Item, '/item/<string:name>') #http://127.0.0.1:5000/item/item_name api.add_resource(ItemList, '/items') api.add_resource(UserRegister, '/register') # this is coming from the user.py file # This ensures that the app file is created # in the same file, and not imported from # some other file. Best Practise
from flask import Flask, request from flask_restful import Resource, Api, reqparse # resource is a thing can be created and changed by API from flask_jwt import JWT, jwt_required from security import authenticate, identity app = Flask(__name__) app.secret_key = 'Raymond' # use a secret key and JWT, which stands for JSON Web Token, to encrypt message -> add security.py api = Api(app) jwt = JWT(app, authenticate, identity) # JWT creates a new endpoint of /auth, including a user name and password, then JWT sent them to authenticate function to compare, and returns a JW token. JWT itself can do nothing, but send to identity function items = [] class Item(Resource): parser = reqparse.RequestParser() parser.add_argument('price', type = float, required = True, #ensure no request can come throught with no price help = "This field cannot be left blank!" ) data = parser.parse_args() @jwt_required() # we have to authenticate before we can call the get method def get(self, name): ### # for item in items: # if item['name'] == name:
from flask import Flask from flask_restful import Api from flask_jwt import JWT from security import authenticate, identity from user import UserRegister from item import Item, ItemList app = Flask(__name__) app.secret_key = 'Flash' api = Api(app) jwt = JWT(app, authenticate, identity) #new endpoint /auth api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(UserRegister, '/register') if __name__ == '__main__': app.run(host='0.0.0.0', port=5565)
from flask import Flask, request from flask_restful import Resource, Api, reqparse from flask_jwt import JWT, jwt_required from security import authenticate, identity app = Flask(__name__) app.secret_key = 'sogeti' # generally this would be hidden api = Api(app) jwt = JWT(app, authenticate, identity) # creates '/auth' endpoint items = [] class Item(Resource): parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help='This field cannot be left blank') @jwt_required() def get(self, name): for item in items: if item['name'] == name: return item return {'item': None}, 404 # not found
from resources.campsite import Campsite, CampsiteList, CampsiteByZipList from resources.zipcode import Zipcode, ZipcodeList from resources.travel_time import TravelTime, TravelTimeList, TravelTimeByZipList from resources.weather_forecast import WeatherForecastList, WeatherForecastForCampsite from db import db app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL", "sqlite:///data.db") # confusing-- I think this keep flask from tracking changes but lets SQLalchemy do it?? app.config["SQLALCHEMY_TRACK_NOTIFICATIONS"] = False app.secret_key = "stuart" api = Api(app) jwt = JWT( app, authenticate, identity ) # JWT will create /auth endpoint... that endpoint will return JWT token api.add_resource(Zipcode, "/zipcode/<string:zipcode>") api.add_resource(Campsite, "/campsite") api.add_resource(CampsiteList, "/campsites/all") api.add_resource(ZipcodeList, "/zipcodes") api.add_resource(TravelTime, "/traveltime") api.add_resource(TravelTimeList, "/traveltimes") api.add_resource(TravelTimeByZipList, "/traveltimes/<string:zipcode>") api.add_resource(CampsiteByZipList, "/campsites/<string:zipcode>") api.add_resource(UserRegister, "/register") api.add_resource(WeatherForecastList, "/forecasts/all") api.add_resource(WeatherForecastForCampsite, "/forecast/<int:campsite_id>") # conditional ensures that app is only run when we run app.py, and not if/when we import it to another file
from security import authenticate, identify from resources.item import Item, ItemList from resources.store import Store, StoreList from resources.user import UserRegister app = Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'jose123' api = Api(app) jwt = JWT(app, authenticate, identify) #/auth api.add_resource(Store, '/store/<string:name>') api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register') @app.error_handler(JWTError) def auth_error_handler(err): return jsonify({ 'message': 'Could not authorize. Did you include a valid Athorization header?' }), 401
from lib.resources.item import Item, ItemList from lib.resources.store import Store, StoreList from db import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = os.environ.get('SKEY') api = Api(app) @app.before_first_request def create_tables(): db.create_all() jwt = JWT(app, authenticate, identity) # /auth <- jwt creates this new endpoint api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(Store, '/store/<string:name>') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register') if __name__ == '__main__': db.init_app(app) app.run(port=5000, debug=True)
from app.user_models import User, Role from .user.user_resource import user_ns from .user.users_resource import users_ns from .topic.topic_resource import topic_ns from .config import config from flask_restplus import Api from flask_jwt import JWT api = Api(version='1.0', title='guanggoo API', description='APIs for guanggoo CMS') mail = Mail() db = SQLAlchemy() moment = Moment() jwt = JWT() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) blueprint = Blueprint('api', __name__, url_prefix='/api') api.init_app(blueprint) api.add_namespace(user_ns) api.add_namespace(users_ns) api.add_namespace(topic_ns) app.register_blueprint(blueprint) mail.init_app(app)
from flask import Flask from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from flask_jwt import JWT app = Flask(__name__) app.config.from_object('config') api = Api(app) db = SQLAlchemy(app) from api.users.models import User jwt = JWT(app, User.authenticate, User.identity) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH') return response from api.users.models import * from api.todos.models import * # Load User Endpoints from api.users.resources import UserListAPI, UserAPI, UserSignupAPI
from flask import Flask, request from flask_jwt import JWT, jwt_required from flask_restful import Resource, Api, reqparse from util.security import authenticate, identity app = Flask(__name__) app.secret_key = 'simple_store' # Should be hidden in production application. api = Api(app) jwt = JWT(app, authenticate, identity) # Created new end point called /auth This will call methods in security class ItemList(Resource): @staticmethod def get_item(name): return items.get(name, dict()) @staticmethod def add_item(name, item): items[name] = item @staticmethod def del_item(name): item = ItemList.get_item(name) if item: del items[name] @staticmethod def get(): return items, 200
from resource.user import UserRest from resource.notice import NoticeRest from resource.category import CategoryRest from flask_cors import CORS import resource.auth as auth from datetime import timedelta import sys app = Flask(__name__) api = Api(app) app.config["SECRET_KEY"] = "JAUSSLUWLSJOJSOWELJSAJOIJSOJ" app.config["JWT_AUTH_URL_RULE"] = "/api/v1/auth" app.config["JWT_EXPIRATION_DELTA"] = timedelta(days=2) jwt = JWT(app, auth.authenticate, auth.indentity) CORS(app, resources={r"/api/*": {"origins": "*"}}) PROJECT_HOME = os.path.dirname(os.path.realpath(__file__)) app.config['ROOT_FOLDER'] = PROJECT_HOME app.config["UPLOAD_FOLDER"] = f"{PROJECT_HOME}/upload/" app.config['IMAGE_FOLDER'] = f"{PROJECT_HOME}/img/" api.add_resource(UserRest, "/api/v1/user", "/api/v1/user/<int:id_user>") api.add_resource(NoticeRest, "/api/v1/notice", "/api/v1/notice/<int:id_notice>") api.add_resource(CategoryRest, "/api/v1/category", "/api/v1/category/<int:id_category>")
from flask_jwt import JWT from security import authenticate, identity from resources.user import UserRegister from resources.items import Item, ItemList from resources.store import Store, StoreList app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'Shekhar' api = Api(app) @app.before_first_request def create_tables(): db.create_all() jwt = JWT(app, authentication_handler=authenticate, identity_handler=identity) #/auth api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(UserRegister, '/user/register') api.add_resource(Store, '/store/<string:name>') api.add_resource(StoreList, '/stores') if __name__ == "__main__": from db import db db.init_app(app) app.run(port=5000, debug=True)
# 이 wrapping 과정을 모르고 있으면 MongoDB에서 bson InvalidDocument 에러로 고생할 수도 있다 app = Flask(__name__) app.config['SECRET_KEY'] = 'super-secret' # JWT security algorithm을 위해 secret key가 필요하다 app.config['JWT_AUTH_URL_RULE'] = '/auth-for-test' app.config['JWT_AUTH_USERNAME_KEY'] = 'id' app.config['JWT_AUTH_PASSWORD_KEY'] = 'pw' # URL rule과 username, password key를 바꿔줄 수 있다 from datetime import timedelta app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=365) # JWT_EXPIRATION_DELTA 옵션에 만료 시간을 설정할 수 있다. 기본값은 5분 JWT(app, authenticate, identity) @app.route('/protected') @jwt_required() # JWT 토큰이 필요함을 명시한다 # JWT 토큰이 없으면 401 UNAUTHORIZED를 반환 def protected(): return jsonify({ 'message': 'This is a protected resource.', 'current_identity': str(current_identity) }) if __name__ == '__main__': app.run(debug=True)
from flask import Flask from flask_restful import Api from flask_jwt import JWT from security import authentication, itendify from user import UserRegister from item import Item, ItemList app = Flask(__name__) app.secret_key = "jay" api = Api(app) jwt = JWT(app, authentication, itendify) api.add_resource(ItemList, '/items') api.add_resource(Item, '/item/<string:name>') api.add_resource(UserRegister, '/register') if __name__ == "__main__": app.run(port=5000, debug=True)
from flask import Flask from flask_restful import Api from flask_jwt import JWT from src.security import authenticate, identity from src.user import UserRegister from src.item import Item, ItemList app = Flask(__name__) app.secret_key = "qwerty" api = Api(app) # configure the endpoint (/auth on default) to a /login endpoint app.config['JWT_AUTH_URL_RULE'] = '/login' # conigure JWT to expire within half an hour jwt = JWT(app, authenticate, identity) # data:{username: ,password: } # configure JTW auth name to be 'email' instead of default 'username' # app.config['JWT_AUTH_USERNAME_KEY'] = 'email' # adds the Api of the item api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(UserRegister, '/register') if __name__ == "__main__": app.run(port=5000, debug=True)
import datetime app = Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['JWT_EXPIRATION_DELTA'] = datetime.timedelta(seconds=1000) app.secret_key = 'jose' api = Api (app) # @app.before_first_request # def create_tables(): # db.create_all() jwt = JWT(app, authenticate, identity) #auth api.add_resource(Store, '/store/<string:name>') api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(StoreList, '/stores') api.add_resource(UserRegister, '/register') if __name__ == '__main__': from db import db db.init_app(app) if app.config['DEBUG']: @app.before_first_request def create_tables(): db.create_all()
from flask_jwt import JWT from flask_restful import Api from security import authenticate, identification from Resources.user import UserRegister from Resources.item import ItemList, Item app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = "Madiov" api = Api(app) @app.before_first_request def create_table(): db.create_all() jwt = JWT(app, authenticate, identification) # /auth api.add_resource(Item, '/item/<string:name>') api.add_resource(ItemList, '/items') api.add_resource(UserRegister, '/register') if __name__ == "__main__": from db import db db.init_app(app) app.run()