def update(self, id, payload): print(payload) task = DB.find_one("Tasks", {"_id": id}) if task: if 'grade' and 'progress' in payload: DB.update("Tasks", {"_id": id}, { "$set": { "title": payload['title'], "deadline": payload['deadline'], "course_d": payload['course_id'], "description": payload['description'], "attachments": payload['attachments'], "grade": payload['grade'], "progress": payload['progress'] } }) else: DB.update("Tasks", {"_id": id}, { "$set": { "title": payload['title'], "deadline": payload['deadline'], "course_d": payload['course_id'], "description": payload['description'], "attachments": payload['attachments'] } }) return jsonify("Task updated") return jsonify("No task matching given id") return jsonify("No task matching given id")
def create_app(config): app = Flask(__name__) app.json_encoder = CustomJSONEncoder CORS(app) DB.init() register_blueprints(app) return app
def create_app(): app = Flask(__name__, static_url_path='', static_folder='../web/static') app.secret_key = 'hack me' DB.init() bcrypt.init_app(app) register_blueprint(app) return app
def delete(self): if not DB.find_one("sinfo", {"name": self.name}): return 0 else: query_result = DB.delete(collection='sinfo', dcname={'name': self.name}) return (query_result.deleted_count)
def profile(profile_id, is_profile_owner=False): user = DB.find_one(collection="Profile", query={'_id': ObjectId(profile_id)}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) me = DB.find_one(collection="Profile", query={"email": current_user.email}) def are_we_friends(entry): return (entry['friend_id'] == me['_id'] and entry['status'] == 'accepted') is_friend = any(filter(are_we_friends, user['friends'])) eventList = [] for events in user['events']: events = DB.find_one(collection='Events', query={'_id': events}) if not events: continue event_dict = { 'title': events['name'], 'start': events['start'].strftime("%Y-%m-%d"), 'end': events['end'].strftime("%Y-%m-%d") } eventList.append(event_dict) if not eventList: eventList = {} return render_template('profile.html', profile=user, events=eventList, is_profile_owner=is_profile_owner, is_friend=is_friend)
class Searches(DB.Model): address = DB.Column('address', DB.String(250), primary_key=True) valid = DB.Column(DB.Integer) last_request = DB.Column(DB.DateTime) zipcode = DB.Column(DB.String(15)) country = DB.Column(DB.String(100)) message = DB.Column(DB.String(250)) def __init__(self, address, valid, last_request, zipcode, country, message): self.address = address self.valid = valid self.last_request = last_request self.zipcode = zipcode self.country = country self.message = message def __repr__(self): return '<Search addres={}, zipcode={}, country={}, valid={}, message={}>'.format( self.address, self.zipcode, self.country, self.valid, self.message) # get the most recent 10 searches given an string to filter @classmethod def query(cls, val): sanit_val = val.replace('%', '\\%').replace('_', '\_') history = DB.session.query(Searches).filter( Searches.address.ilike('%' + sanit_val + '%')).order_by( Searches.last_request.desc()).limit(10) result = [] for h in history: result.append(h.address) return result
def reset_pwd(token): try: serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) email = serializer.loads(token, salt=app.config['SECRET_KEY']) except: flash('Reset link is invalid or expired') return redirect(url_for('login')) form = PasswordForm() if form.validate_on_submit(): form.password.data = form.password.data.strip() user = DB.find_one(collection="User", query={"email": email}) if user is None: flash('Invalid account!') return redirect(url_for('login')) else: new_password = generate_password_hash(form.password.data) DB.update_one(collection="User", filter={"email": email}, data={"$set": { "password": new_password }}) return redirect(url_for('login')) return render_template('reset-password-token.html', form=form, token=token, email=email)
def delete(self, id): task = DB.find_one("Tasks", {"_id": id}) if task: DB.remove("Tasks", {"_id": id}) return jsonify("Task removed") return jsonify("No task matching given id")
def create_app(config): app = Flask(__name__) DB.init() scheduler = Scheduler(seconds=900) with app.app_context(): scheduler.start_scheduler() register_blueprints(app) return app
def create_app(config): app = Flask(__name__) DB.init() register_blueprints(app) for job_name in ['job1', 'job2', 'job3']: new_job = Job(name=job_name) new_job.insert() return app
def update_student(id): student = DB.find_one("Students", {"_id": id}) sync = request.args.get('sync') if student and sync and sync == 'true': last_sync_date = datetime.datetime.utcnow() DB.update("Students", {"_id": id}, { "$set": {"last_sync_date": last_sync_date}}) return jsonify("Successfully upadted the student information") return jsonify("No student matching given id")
def insert(self): if not DB.find_one("Profile", {"polls._id": self.creator}): poll = DB.insert(collection='Poll', data=self.json()) DB.update_one(collection='Profile', filter={'_id': self.creator}, data={'$push': { 'polls': poll.inserted_id }}) return poll.inserted_id
def update_db(initial_num): a = DB.find_one("dianping_register", {"crawby": "jack"}) if a: DB.update("dianping_register", {"crawby": "jack"}, { '$set': {'initial_num': initial_num}}) else: DB.insert('dianping_register', { "crawby": "jack", 'initial_num': initial_num}) pass
def edit_event(eventId): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) event = DB.find_one(collection="Events", query={"_id": ObjectId(eventId)}) if event is None: flash('Please contact admin, DB issues!') return redirect(url_for('view_events')) form = EventForm() if form.validate_on_submit(): if form.pictureDir.data is not None: if event['pictureDir'] == 'event.jpg': filename = photos.save(form.pictureDir.data, name='event/' + str(event['_id']) + '.') filename = filename.split('/')[1] else: # delete existing photo filename = "app/static/images/event/" + event['pictureDir'] os.remove(os.path.join(filename)) filename = photos.save(form.pictureDir.data, name='event/' + str(event['_id']) + '.') filename = filename.split('/')[1] DB.update_one(collection="Events", filter={"_id": event['_id']}, data={"$set": { "pictureDir": filename }}) if form.eventType.data == 'private': event_type = True else: event_type = False DB.update_one(collection="Events", filter={"_id": event['_id']}, data={"$set": { "name": form.name.data.strip() }}) DB.update_one( collection="Events", filter={"_id": event['_id']}, data={"$set": { "description": form.description.data.strip() }}) DB.update_one(collection="Events", filter={"_id": event['_id']}, data={"$set": { "private": event_type }}) return redirect(url_for('view_events')) return render_template('edit-event.html', title="Edit Event Details", form=form, event=event)
def setUp(self): app.config["TESTING"] = True db = DB("hfa_events_test") db.init_db() self.db = db app.config.update({"db": db}) app.config["db"].session.query(Location).delete() app.config["db"].session.query(Attendee).delete() app.config["db"].session.query(Event).delete()
def delete_poll(poll): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) toDelete = DB.find_one(collection='Poll', query={'_id': ObjectId(poll)}) if toDelete is None: flash('Please contact admin, DB error!') return redirect(url_for('polls')) for voter in toDelete['voters']: toRemove = DB.find_one(collection="Profile", query={"_id": voter}) if toRemove is None: flash('Please contact admin, DB error!') return redirect(url_for('polls')) DB.update_one(collection="Profile", filter={'_id': voter}, data={"$pull": { "polls": ObjectId(poll) }}) DB.update_one(collection="Profile", filter={'_id': user['_id']}, data={"$pull": { "polls": ObjectId(poll) }}) DB.remove(collection="Poll", condition={"_id": ObjectId(poll)}) flash('Deleted Poll!') return redirect(url_for('polls'))
def create_app(config_name): app = Flask(__name__) app.config.from_object( app_config[config_name] ) #Updates the values from the given object : Load Configuration Defaults logging.basicConfig(filename='flask.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s : %(message)s') DB.init() register_blueprints(app) return app
def updatecertificate(): if request.method == 'POST': username = session.get('user') updatetext = request.form['updatetxt'] collection = 'Certifications' query = {'Email': username} newvalues = {"$push": {'certificates': updatetext}} DB.update_one(collection, query, newvalues) flash("Certificate Successfully Updated") return render_template('home.html', username=session.get('user'), personal=None, academic=None)
class SampleTable(DB.Model): id = DB.Column(DB.Integer, primary_key=True) inserted_at = DB.Column(DB.DateTime) message = DB.Column(DB.String(250)) def __init__(self, id, val): self.id = id self.value = val self.inserted_at = "now()" def __repr__(self): return '<Search id={}, inserted_at={}, value={}'.format( self.id, self.inserted_at, self.value)
class Temperatures(DB.Model): zipcode = DB.Column('zipcode', DB.String(15), primary_key=True) value = DB.Column(DB.JSON) last_request = DB.Column(DB.DateTime) def __init__(self, zipcode, value, last_request): self.zipcode = zipcode self.value = value self.last_request = last_request def __repr__(self): return '<Temperature zipcode={}, last_request={}, temperature={}, location={}>'.format( self.zipcode, self.last_request, self.value['temperature'], self.value['location'])
def insert(self): if not DB.find_one( collection_mapPoints, { 'provider': self.provider, 'location': { 'type': "Point", 'coordinates': [self.latitude, self.longitude] }, 'signalStrength': self.signalStrength, 'signalType': self.signalType, 'time': self.time, 'dbAddDate': self.dbAddDate }): DB.insert(collection=collection_mapPoints, data=self.json())
def get_initial_num(): a = DB.find_one("dianping_register", {"crawby": "jack"}) b = DB.find_one("Ratings", {"source": "dazhongdianping"}) if a: initial_num = a['initial_num'] elif b: c = DB.find_max( 'Ratings', {"source": "dazhongdianping"}, 'timestamp') if c: initial_num = b['reviewId'] else: initial_num = 706754427 else: initial_num = 706754427 return initial_num
def upload(self, files): files_result = [] for file in files: file_id = DB.save_file(file, file.filename) file_obj = {"_id": str(file_id), "filename": file.filename} files_result.append(file_obj) return jsonify(files_result)
def updateacademic(): if request.method == 'POST': print(session.get('user')) username = session.get('user') updatecol = request.form['updateinfo'] updatetext = request.form['updatetxt'] collection = 'AcademicInfo' query = {'Email': username} newvalues = {"$set": {updatecol: updatetext}} print(updatecol, updatetext) DB.update_one(collection, query, newvalues) flash(updatecol + " Successfully Updated") return render_template('home.html', username=session.get('user'), personal=None, academic=None)
def create_app(new): app = Flask(__name__) bootstrap = Bootstrap(app) app.config.from_object(Config) #根据config启用mongodb if Config.MongoDbEnable: DB.init() for job_name in ['job1', 'job2', 'job3']: new_job = Job(name=job_name) new_job.insert() sentence2vec.init() NewsData.init() register_blueprints(app) return app
def mean(attribute): if request.method == 'GET': limit = request.args.get('limit', default=20, type=int) visitor_key = request.args.get('visitor_key', default=None, type=str) if visitor_key: query = {"visitor_key": visitor_key} else: query = None projection = [attribute] data = DB.find(collection, query, projection, limit=limit) accum = 0 count = 0 for result in data: accum += result[attribute] count += 1 if count == 0: return jsonify({ 'ok': False, 'message': 'No results matching criteria!' }), 400 return jsonify({'value': accum / count}), 200
def insert(self): try: if not DB.find_one("sinfo", {"name": self.name}): # try: id = DB.insert(collection='sinfo', data=self.json()).inserted_id return (id, 204) # except pymongo.errors.ConnectionFailure as e: # return jsonify({'ok': False, 'message': str(e)}), 500 # else: #return jsonify({'ok': True, 'message': "Name already exist for {}".format(self.name))}), 400 except: e = sys.exc_info()[0] # print(e) #return ('ok': True, 'message': "Name already exist for {}".format(self.name)}, 400 return (e, 402)
def searchsecondyear(): collection = 'PersonalInfo' query = {} personal = DB.find_many(collection, query) return render_template('adminhome.html', username=session.get('user'), personal=personal)
def get_name(email): return DB.find_one(collection="Profile", query={"email": email}, projection={ "firstName": 1, "lastName": 1 })
def modify_product_fields(product_code): if not app.config['DISABLE_TOKEN'] and not __check_authorization(): return jsonify({'error': 'Need a valid token.'}) product = request.get_json() if not product: return Response('Missing parameters', 422, mimetype='application/json') try: DB.find_one_and_update('products', {'product_code': product_code}, product) return Response('Successfully Replaced', 201, mimetype='application/json') except ValueError: return Response('Failed to replace the product.', 422, mimetype='application/json')
def login(): if current_user.is_authenticated: return redirect(url_for('dashboard')) form = LoginForm() if form.validate_on_submit(): form.email.data = form.email.data.strip() user = DB.find_one(collection="User", query={"email": form.email.data}) if user and check_password_hash(user['password'], form.password.data): if user['confirmed']: user_obj = User(email=user['email'], password=user['password'], confirmed=user['confirmed']) # print(user_obj.email) login_user(user_obj) # flash(user_obj.name) return redirect(url_for('dashboard')) # next_page = request.args.get('next') # if not next_page or url_parse(next_page).netloc != '': # next_page = url_for('index') # return redirect(next_page) else: flash('Please confirm your email') return redirect(url_for('login')) else: flash("Invalid email or password") return render_template('login.html', title='Log In', form=form)
def alarm_sync(): db =DB() client.get_token() while True: try: time.sleep(10) lastid = db.get_sync_id() events = client.get_alarm(lastid) if events == None: client.get_token() continue else: if events == []: #log.debug("not has any event") continue for one in events: log.debug(one) db.save_event(one["id"], one["type"],one["deviceid"],one["zwavedeviceid"],one["eventtime"],one["objparam"]) except: import traceback traceback.print_exc() continue
from app.server import app from app.database import DB if __name__ == "__main__": db = DB("hfa_events_dev") db.init_db() app.config.update({"db": db}) app.run(host="0.0.0.0")