class SubmissionDownload(Resource): @login_required def get(self, id): subm = Submission.objects.get_or_404(id=id) proj = subm.project course = proj.course if g.user == subm.submitter or g.user in course.teachers: response = make_response(subm.code.read()) response.headers['Content-Type'] = subm.code.content_type response.headers[ 'Content-Disposition'] = 'attachment; filename="{0}"'.format( subm.code.filename) return response else: abort( 403, message= "Only submitter or course teacher can download submission code." ) api.add_resource(SubmissionDownload, '/submission/<string:id>/download', endpoint='submission_download_ep') api.add_resource(SingleSubmission, '/submission/<string:id>', endpoint='submission_ep') api.add_resource(SingleSubmissionRun, '/submission/<string:id>/run', endpoint='submission_run_ep')
from flask.ext.restful import Resource, marshal_with, abort from flask import g, make_response class TeamProjectGrades(Resource): @login_required @marshal_with(team_project_grade_fields) def get(self): """ Lists all submissions related to the course. """ if isinstance(g.user, Student): return TeamProjectGrade.objects(team_id=g.user.team_id) else: abort(403, message="Must be a student to view grades") class Foo(Resource): def get(self): return {'hello': 'world'} def post(self): return {'hello': 'world'} api.add_resource(TeamProjectGrades, '/teamgrades', endpoint='team_project_grade_ep') api.add_resource(Foo, '/testfoo', endpoint='test_grade_ep')
item.account_id = json["accountId"] db.session.commit() return item.serialize() @staticmethod def delete(item_id): user = flask_login.current_user item = Item.query.filter(Item.id == item_id, Item.user_id == user.id).first_or_404() item.is_active = False db.session.commit() return 200 # Paths api.add_resource(AccountsListResource, "/api/accounts") api.add_resource(AccountsResource, "/api/account/<int:account_id>") api.add_resource(CategoryListResource, "/api/categories") api.add_resource(CategoriesResource, "/api/category/<int:category_id>") api.add_resource(ItemListResource, "/api/items") api.add_resource(ItemResource, "/api/item/<int:item_id>") @app.route("/api/dashboard", methods=['GET']) def dashboard(): user = flask_login.current_user accounts = Account.query.filter(Account.is_active == True, Account.user_id == user.id).all()
'Accept-Encoding':'gzip, deflate, sdch', 'Connection':'keep-alive', 'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36' } r = requests.post(self.urlLogin, data=post, cookies=arg['dtcookie'], headers=header) self.saveDb('getLogout', header, post, r.headers, r.text) return 'Logout' def saveDb(self, name, rqHead, rqPost, rsHead, rsData): data = { 'name':name, 'requestHeader':dumps(rqHead), 'requestData':dumps(rqPost), 'responseHeader':dumps(rsHead), 'responseData':dumps(rsData), 'timestamp':datetime.now() } insert = { name : data } cmongo = self.cmongo if name == 'getCookie': dtId = cmongo.insert(insert) self.dtId = dtId else: cmongo.update({'_id':self.dtId}, {"$set": insert}, upsert=False) return self.dtId api.add_resource(Crawler_BCA, '/bca/crawler')
from application.resources.TeamMateList import TeamMateList from application.resources.TeamMate import TeamMate from application import app, api api.add_resource(TeamMateList, '/teammates') api.add_resource(TeamMate, '/teammates/<login>') if __name__ == '__main__': app.run(debug=True)
from PIL import Image from io import BytesIO import requests from pprint import pprint from application import db, api from application.models.travel_info import TravelInfo from application.schemata.travel_info import TravelInfoSchema from flask import Blueprint, request, Response, make_response, render_template, url_for, current_app from flask_restful import Resource import boto3 from boto3.dynamodb.conditions import Key, Attr travel_info_bp = Blueprint("info", __name__, url_prefix='/info') info_schema = TravelInfoSchema() session = db.session api = api(travel_info_bp) dynamodb = boto3.resource('dynamodb', region_name='ap-southeast-2') TableInformation = dynamodb.Table('ChatBotForInformation') TableSearch = dynamodb.Table('ChatBotForSearch') class Info(Resource): def get(self, contentID=None): if contentID is None: return make_response( render_template('display_result.html', title='no data', addr='no data', phone_number='no data', overview='no data', image='no data'), 200) res = TableInformation.get_item(Key={'contentID': contentID})
def put(self, merchant_id): args = parser.parse_args() mongo.db.merchants.update( { '_id' : ObjectId(merchant_id) } , { '$set' : args } ) return to_json(mongo.db.merchants.find_one( { '_id' : ObjectId(merchant_id) } )) def delete(self, merchant_id): mongo.db.merchants.remove( { '_id' : ObjectId(merchant_id) } ) return { 'success' : True } class MerchantList(restful.Resource): def get(self): results = mongo.db.merchants.find() json_result = [] for result in results: json_result.append(result) return to_json(json_result) def post(self): args = parser.parse_args() oid = mongo.db.merchants.insert(args) return to_json(mongo.db.merchants.find_one( { '_id' : oid } )) api.add_resource(Merchant, '/merchants/<string:merchant_id>') api.add_resource(MerchantList, '/merchants') #https://ep2013.europython.eu/conference/talks/developing-restful-web-apis-with-python-flask-and-mongodb
user=request_user), 201, headers) if id is not None: target_user = User.query.get(id) used_vacation = UsedVacation.query.filter_by( user=target_user).all() if id != data.get('id'): target_id = data.get('사용자 번호') return make_response( render_template('user/select_specific_user.html', title='사용자 정보', result=used_vacation, target_id=str(target_id), id=str(request_user.id)), 200, headers) else: return make_response( render_template('user/multiple_user_result.html', title="사용한 휴가", result=used_vacation, id=str(target_user.id), user=request_user), 201, headers) def post(self, id=None): google_service.run() return redirect(url_for('main')) api.add_resource(UserUsedVacation, '/used', '/<string:id>/used', endpoint='used')
return redirect(url_for('user', username=user.username)) @app.route('/unfollow/<string:username>') @login_required def unfollow(username): user = User.query.filter_by(username=username).first() if user is None: flash('Invalid User', 'error') return redirect(url_for('dashboard')) current_user.unfollow(user) flash('You have successfully unfollwed {username}'.format(username=user.username), 'success') return redirect(url_for('user', username=user.username)) @app.route('/followers/<username>') @login_required def followers(username): user = User.query.filter_by(username=username).first() if user is None: flash('Invalid user.', 'error') redirect(url_for('dashboard')) page = request.args.get('page', default=1, type=int) pagination = user.followers.paginate(page, per_page=current_app.config['FOLLOWERS_PER_PAGE'], error_out=False) follows = [{'user':item.follower, 'follow_date':item.follow_date} for item in pagination.items] return render_template('followers.html', user=user, title='Followers of', endpoint='followers', pagination=pagination, follows=follows) api.add_resource(PostApi, '/api/post','/api/post/<int:id>' ) api.add_resource(AuthApi, '/api/auth')
raw = BeautifulSoup(r.text) self.captcha = raw.find('img',{'id':'IMAGECAPTCHA'}).attrs.get('src') captcha = self.url+self.captcha return captcha # def saveDb(self, name, rqHead, rqPost, rsHead, rsData): # data = { # 'name':name, # 'requestHeader':dumps(rqHead), # 'requestData':dumps(rqPost), # 'responseHeader':dumps(rsHead), # 'responseData':dumps(rsData), # 'timestamp':datetime.now() # } # insert = { # name : data # } # cmongo = self.cmongo # if name == 'getCookie': # # insert data # dtId = cmongo.insert(insert) # self.dtId = dtId # else: # # update data # cmongo.update({'_id':self.dtId}, {"$set": insert}, upsert=False) # return self.dtId api.add_resource(Crawler_BNI, '/bni/crawler')
from application import api, app, jsonify, render_template, request, make_response from application.rest import msUserResources from application.rest import helloWorldResources @app.route('/') def index(): return render_template('index.html') @app.route('/info') def info(): return 'info' # ----------------------- ADD REST ----------------------- api.add_resource(helloWorldResources.HelloWorldEndpoint, '/hello') api.add_resource(helloWorldResources.SecretInformation, '/secret') api.add_resource(msUserResources.UserRegistration, '/register') api.add_resource(msUserResources.AllUsers, '/msusers')
"""Returns true if file with name filename is allowed.""" return '.' in filename and filename.rsplit( '.', 1)[1] in app.config['ALLOWED_CODE_EXTENSIONS'] def allowed_test_file(filename): """Returns true if file with name filename is allowed.""" return '.' in filename and filename.rsplit( '.', 1)[1] in app.config['ALLOWED_TEST_EXTENSIONS'] def allowed_class_file(filename): """Returns true if file with name filename is allowed.""" return '.' in filename and filename.rsplit( '.', 1)[1] in app.config['ALLOWED_TEST_EXTENSIONS'] class ClearDB(restful.Resource): def get(self): from application.models import Project, User, Student, Course, Submission Submission.objects.delete() Project.objects.delete() Course.objects.delete() Student.objects.delete() User.objects.delete() return {}, 200 if app.config['DROP_ENDPOINT']: api.add_resource(ClearDB, '/drop', endpoint='drop_db_ep')
from flask import Blueprint from application import api from application.views import (Index, ClassAdd, StudentDetail, StudentAdd, StudentDel, StudentHide, StudentList) index_bp = Blueprint('index', __name__) api.add_resource(Index, "/") # 检测app是否正常 api.add_resource(ClassAdd, "/class/add") # 添加班级 api.add_resource(StudentAdd, "/class/<cid>/student/add") # 添加学生 增 api.add_resource(StudentDel, "/student/delete/<sid>") # 删除学生 删 api.add_resource(StudentHide, "/student/hide/<sid>") # 隐藏一条数据 改 api.add_resource(StudentDetail, "/student/<sid>") # 查看学生信息 查 api.add_resource(StudentList, "/class/<cid>/students") # 查看某班所有学生
""" Computes grade. """ project = Project.objects.get_or_404(id=project_id) course = project.course if g.user not in course.teachers: abort(403, message="Must be course teacher to compute grades.") if not project.can_submit: abort(422, message="Can only compute grades when we are past the deadline.") rerurn_submissions_bool = rerurn_submissions == "yes" compute_team_grades.delay(str(project.id), rerurn_submissions_bool) api.add_resource( ProjectTestFileDownload, '/project/<string:project_id>/tests/<string:name>', endpoint="project_test_file_ep") api.add_resource(ProjectSubmissions, '/course/<string:course_name>/projects/<string:name>/submissions/<int:page>', endpoint='project_submissions_ep') api.add_resource(ProjectGrades, '/project/<string:id>/grades/<string:rerurn_submissions>/<int:page>', endpoint='project_grades_ep') api.add_resource( ProjectResource, '/project/<string:id>', endpoint='project_ep') api.add_resource(ProjectsResource, '/projects', endpoint='projects_ep')
db.session.commit() def delete(self, id): user = User.query.get(id) remain_vacation = RemainVacation.query.filter_by(user=user).delete() db.session.commit() return Response(remain_vacation_schema.dumps(remain_vacation), 200, mimetype='application/json') api.add_resource(UserVacation, '/remain', '/<string:id>/remain', endpoint='user_vacation') def calculate_vacation(user): user = user years = datetime.datetime.today().year - user.entry_date.year if years != 0: total = 15 + (years // 2) else: working_day = (datetime.datetime(user.entry_date.year, 12, 31) - user.entry_date).days vacation = (15 * (working_day / 365)) if not calendar.isleap( user.entry_date.year) else (15 * ((working_day + 1) / 366)) flag = vacation - int(vacation)
img_grey = ImageOps.grayscale(img_rgb) img_rbg = np.array(img_rgb) img_grey = np.array(img_grey) img_res = conversion(img_rbg,img_grey) img_byte_arr = io.BytesIO() img_res.save(img_byte_arr, format='png') img_byte_arr = img_byte_arr.getvalue() # return send_file( # img_byte_arr, # mimetype='image/jpeg', # as_attachment = True, # attachment_filename='image.jpg' # ) response = make_response(img_byte_arr) response.headers.set('Content-type','image/png') response.headers.set( 'Content-Disposition','attachment',filename='image.png' ) return response api.add_resource(image_return, "/image")
""" urls.py URL dispatch route mappings and error handlers """ from flask import render_template from application import app, api from application.ressources import bill, client, currency, invoice, ledger, payout, rate, session, settlement, subscription, token api.add_resource(bill.BillHandler, '/bills', '/bills/<string:bill_id>', '/bills/<string:bill_id>/deliveries') api.add_resource(bill.BillDeliveryHandler, '/bills/<string:bill_id>/deliveries') api.add_resource(client.ClientHandler, '/clients', '/clients/<string:key_id>') api.add_resource(currency.CurrencyHandler, '/currencies') api.add_resource(invoice.InvoiceHandler, '/invoices', '/invoices/<string:invoice_id>') api.add_resource(invoice.InvoiceEventHandler, '/invoices/<string:invoice_id>/events') api.add_resource(invoice.InvoiceRefundHandler,'/invoices/<string:invoice_id>/refunds', '/invoices/<string:invoice_id>/refunds/<string:request_id>') api.add_resource(invoice.InvoiceNotificationHandler, '/invoices/<string:invoice_id>/notifications') api.add_resource(ledger.LedgerHandler, '/ledgers/<string:currency>', '/ledgers') api.add_resource(payout.PayoutHandler, '/payouts', '/payouts/<string:payout_id>') api.add_resource(rate.RateHandler, '/rates', '/rates/<string:base_currency>', '/rates/<string:base_currency>/<string:currency>') api.add_resource(session.SessionHandler, '/sessions') api.add_resource(settlement.SettlementHandler, '/settlements', '/settlements/<string:settlement_id>') api.add_resource(settlement.SettlementReconciliationHandler, '/settlements/<string:settlement_id>/reconciliationReport') api.add_resource(subscription.SubscriptionHandler, '/subscriptions', '/subscriptions/<string:subscription_id>') api.add_resource(token.TokenHandler, '/tokens') from flask import jsonify # Error handlers # Handle 404 errors
auth = request.headers.get('X-Auth', None) if auth is not None: auth = auth.replace('Basic ', '', 1) try: auth = base64.b64decode(auth) values = auth.split(':') if len(values) != 2: abort(400, message="Malformed X-Auth Header.") user = User.objects(email__iexact=values[0]) if len(user) != 1: abort(401, message='Invalid email or password') else: user = user[0] if app.config['ENABLE_EMAIL_ACTIVATION'] and not user.active: abort(422, message='Inactive user') if user.verify_pass(values[1]): remember = token_parser.parse_args()['remember'] duration = 12 * 30 * 24 * 60 * 60 if remember == 'true' else 10 * 60 token = user.generate_auth_token(duration) return marshal({"token": token, "valid_for": duration, "user": user.to_dict()}, token_fields), 201 else: abort(401, message='Invalid email or password') except TypeError: # Wasn't a base 64 string abort(400, message="Not a base 64 string") else: abort(400, message="Missing X-Auth field") api.add_resource(TokenResource, '/token', endpoint='token_ep')
for jzksignup_info in jzksignup_infos: if dict['pid'] == str(jzksignup_info.pid): reqs['msg'] = "您已经报名,请勿重复报名" return jsonify(reqs) signup = JzkSignUp(uid=uid, pid=dict['pid'], is_confirme=1) db.session.add(signup) db.session.commit() return jsonify(reqs) def delete(self): pass api.add_resource(userMessage, "/api/userMessage/") api.add_resource(userGroup, "/api/userGroup/") api.add_resource(part_time, "/api/part_time/") api.add_resource(sign_up, "/api/sign_up/") api.add_resource(inform, "/api/inform/") api.add_resource(advertising, "/api/advertising/") api.add_resource(app_posts, "/api/app_posts/") api.add_resource(business, "/api/business/") api.add_resource(app_detal, "/api/getdetal/") api.add_resource(app_me, "/api/getme/") api.add_resource(app_user_message, "/api/getmemessages/") api.add_resource(app_collection, "/api/getcollect/") api.add_resource(enroll, "/api/getenroll/")
def post(self): """ Créer un post """ new_post = Post( title=request.json["title"], author=request.json["author"], content=request.json["content"], date=request.json["date"] ) db.session.add(new_post) db.session.commit() return post_schema.dump(new_post) api.add_resource(PostListResource, "/posts/") class PostResource(Resource): def get(self, post_id): """ Obtenir un post dans la base de données """ post = Post.query.get_or_404(post_id) return post_schema.dump(post) def patch(self, post_id): """ Modifier un post """ post = Post.query.get_or_404(post_id)
abort(400, message="published value must be True or False as string.") if args['is_quiz'] == 'True': project.is_quiz = True elif args['is_quiz'] == 'False': project.is_quiz = False else: abort(400, message="is_quiz value must be True or False as string.") project.save() course.projects.append(project) course.save() return marshal(project.to_dict(parent_course=course), project_fields), 201 api.add_resource(CourseProjects, '/course/<string:name>/projects', endpoint='course_projects_ep') api.add_resource(CoursesResource, '/courses/<int:page>', endpoint='courses_ep') api.add_resource(CourseResource, '/course/<string:name>', endpoint='course_ep') api.add_resource(CourseStudents, '/course/<string:name>/students/<int:page>', endpoint='course_students_ep') api.add_resource(CourseTeachers, '/course/<string:name>/tas/<int:page>', endpoint='course_tas_ep') api.add_resource(CourseSubmissions, '/course/<string:name>/submissions/<int:page>', endpoint='course_submissions_ep')
@marshal_with(student_quiz_grade_fields) def get(self): """ Lists all grades related to the user. """ if isinstance(g.user, Student): quiz_grades = [ grade.to_dict() for grade in StudentQuizGrade.objects(student=g.user) ] return quiz_grades else: abort(403, message="Must be a student to view grades") api.add_resource(UsersResource, '/users', endpoint='users_ep') api.add_resource(UserResource, '/user/<string:id>', endpoint='user_ep') api.add_resource(UserSubmissions, '/user/<string:id>/submissions', endpoint='user_submissions_ep') api.add_resource(UserGrades, '/user/grades', endpoint='user_grades_ep') api.add_resource(UserTeamProjectGrades, '/user/team_grades', endpoint='user_team_grades_ep') api.add_resource(UserQuizGrades, '/user/quiz_grades', endpoint='user_quiz_grades_ep') api.add_resource(UserMilestoneGrades, '/user/milestone_grades', endpoint='user_milestone_grades_ep') api.add_resource(UserActivation, '/activate', endpoint='activation_ep')
import pprint from application import app, api, auth from flask import jsonify, request from flask_restful import Resource class Index(Resource): @auth.requires_auth def get(self): return { 'status':'true', 'message':'Welcome Oemah', } # error handler @app.errorhandler(404) def not_found(error=None): message = { 'Status': 404, 'Error': 'Not Found ' + request.url, } resp = jsonify(message) resp.status_code = 404 return resp api.add_resource(Index, '/')
if data.get('admin'): # 일반 사용자는 admin 수정 불가 return Response("No Authority", 401, mimetype='application/json') session.commit() return Response(user_schema.dumps(target_user), 200, mimetype='application/json') def delete(self, id): request_user = User.query.get(request.form['id']) if not request_user.admin: return Response(user_schema.dumps(request_user), 401, mimetype='application/json') target_user = User.query.get(id) if not target_user or target_user.admin: # 삭제하려는 대상이 존재하지 않는 경우 return Response(user_schema.dumps(target_user), 400, mimetype='application/json') db.session.delete(target_user) db.session.commit() return Response(user_schema.dumps(request_user), 200, mimetype='application/json') def post(self, id=None): data = request.form user = User.query.all() target_id = "temp" if not data.get('사용자 번호') else data.get('사용자 번호') return make_response(render_template('user/select_specific_user.html', title="회원 선택", result=user, id=str(data.get('id')), target_id=target_id), 200, headers) api.add_resource(AllUsers, '/') api.add_resource(SpecificUser, '/<string:id>')
# portfolio from esg.resources.portfolio_resource import PortfolioModelList from esg.resources.tag_history_resource import TagHistory from esg.resources.tag_type_resource import TagsByTags from esg.resources.esg_charts_resource import EsgChartsRouting # company from esg.resources.data_provider_resource import DataProviderList from esg.resources.company_resource import CompanyList, CompanyESGSummary # data management from esg.resources.data_management_resource import PortfolioDataManager app.register_blueprint(app_esg.bp) # api.add_resource(NoteResource, '/api/note', '/api/note/<keyword>') # authorization api api.add_resource(UserLogon, '/api/auth/logon') api.add_resource(UserLogoff, '/api/auth/logoff') api.add_resource(UserProfile, '/api/auth/user_profile') # portfolio api api.add_resource(PortfolioModelList, '/api/portfolio/list') api.add_resource(TagHistory, '/api/tags/tag_history') api.add_resource(TagsByTags, '/api/tags/by_tags') api.add_resource(EsgChartsRouting, '/api/esg_charts') # company api api.add_resource(DataProviderList, '/api/data_provider_list') api.add_resource(CompanyList, '/api/company_list') api.add_resource(CompanyESGSummary, '/api/company_esg_summary/<data_provider_id>/<company_id>') api.add_resource(CompanyESGSummary, '/api/company_esg_summary',
args = dict([(key, value) for (key, value) in args.items() if key is not None]) if 'page' not in args: abort(400, message="must specify page") if not any(key in args for key in ['student_id', 'team_id', 'project_id']): abort(400, message="must have at least one query field") students = Student.objects( db.Q(team_id=args.get('team_id')) | db.Q(guc_id=args.get('guc_id'))) if 'project_id' in args: if len(students) > 0: subs = (Submission.objects( submitter__in=students, project=Project.objects(id=args['project_id'])).order_by( '-created_at').paginate(args['page'], per_page)) else: subs = (Submission.objects(project=Project.objects( id=args['project_id'])).order_by('-created_at').paginate( args['page'], per_page)) else: subs = Submission.objects( submitter__in=students).order_by('-created_at').paginate( args['page'], per_page) return mongo_paginate_to_dict(subs, 'submissions') api.add_resource(SubmissionSearch, '/search/submissions', endpoint='submission_search')
non_collection = None if collectionname: collection = ( non_collection if collectionname == the_non_collection else retrieve_dbo(Collection, collectionname) ) return [ sensor.flot_repr() for sensor in Sensor.query.filter(Sensor.collection == collection).order_by(Sensor.name.asc()).all() if _chk_sens(sensor) ] return sorted( set( [ sensor.collection.name if sensor.collection != non_collection else the_non_collection for sensor in Sensor.query.all() if _chk_sens(sensor) ] ) ) api.add_resource(AxisHandler, "/axis", "/axis/") api.add_resource(CollectionHandler, "/collection", "/collection/", "/collection/<string:name>") api.add_resource(ConcHandler, "/%", "/%/", "/<int:cc>", "/<float:cc>", "/<int:cc>/", "/<float:cc>/") api.add_resource(DataHandler, "/data", "/data/", "/data/<string:sensorname>") api.add_resource(GraphHandler, "/graph", "/graph/", "/graph/<string:collectionname>") api.add_resource(SensorHandler, "/sensor", "/sensor/", "/sensor/<string:name>") api.add_resource(SpaceHandler, "/space", "/space/") api.add_resource(UnitHandler, "/unit", "/unit/", "/unit/<string:name>")
from application import app, api from data import db_session, views from api.video_resources import VideoResource from api.user_resources import * import os if __name__ == '__main__': if not os.path.isdir(app.config['DB_FOLDER']): os.mkdir(app.config['DB_FOLDER']) db_session.global_init(app.config['DB_PATH']) api.add_resource(VideoResource, '/api/video/<int:video_id>') api.add_resource(RegisterResource, '/api/register') api.add_resource(LoginResource, '/api/login') app.run()