def send_notification(order, template, method): """ Send notification by specified method :order: the order which the notification is related to :template: the template to use :method: send notification by which method """ user = order.user order_info = dict(order_id=order.id, order_timestamp=order.timestamp, order_description=order.description, username=user.nickname) if method == SEND_METHOD_EMAIL: subject = template.email_subject.format(**order_info) body = template.email.format(**order_info) send_job = q.enqueue(send_email, user.email, subject, body) elif method == SEND_METHOD_SMS: send_job = q.enqueue(send_sms, user.mobile, template.sms.format(**order_info)) elif method == SEND_METHOD_APP: send_job = q.enqueue(send_app_push, user, template.app.format(**order_info)) # log after sending job done. q.enqueue_call(add_log, args=(order, template, method), depends_on=send_job)
def send_to_phyloviz(self, job_ids, dataset_name, dataset_description, additional_data, database_to_include, database_version, max_closest, user_id, species_id, missing_data, missing_char, phyloviz_user, phyloviz_pass, makePublic): job = q.enqueue_call(func=phyloviz_functions.send_to_phyloviz, args=( job_ids, dataset_name, dataset_description, additional_data, database_to_include, database_version, max_closest, user_id, species_id, missing_data, missing_char, phyloviz_user, phyloviz_pass, makePublic, ), result_ttl=5000, timeout=600) return job.get_id()
def run_watching(): if current_user.is_authenticated: group = Group.query.filter_by(user_id=current_user.id).first() if group is not None: job = q.enqueue_call(func=parse_post_loop, args=(group, ), result_ttl=500, timeout=600000)
def process(): url = json.loads(request.data.decode())['url'] job = q.enqueue_call( func=count_and_save_words, args=(url,), result_ttl=5000 ) return job.get_id()
def send_page_to_kindle(): """Public api to send webpage to kindle. :return: Json success response :raises RequestException: API errors """ context = {} required_params = ('url', 'token') if request.json and all( [param in request.json for param in required_params]): url = request.json['url'] token = request.json['token'] elif request.args and all( [param in request.args for param in required_params]): url = request.args['url'] token = request.args['token'] else: raise RequestException('Missing parameters', 400) context['url'] = url user = User.query.filter_by(api_token=token).first() if not user: raise RequestException('No matching token found.', 401) if not user.verified: raise RequestException('You have not verified your email adress.', 401) context['kindle_email'] = user.kindle_email if url: # Will raise exception is page doesn't exist or there's a problem requests.get(url, allow_redirects=True) q.enqueue_call(func=scrape_and_send, args=(url, user.kindle_email), result_ttl=5000) if request.json: return {'success': True}, 200 else: return render_template('sent.html', context=context)
def reset_password(): user = User.get(User.email == request.form['emailresetpw']) min_char = 8 max_char = 12 allchar = string.ascii_letters + string.punctuation + string.digits user_password = "".join( choice(allchar) for x in range(randint(min_char, max_char))) user.password = user_password if user.save(): q.enqueue_call(func=reset_password_email, args=( user, user_password, ), timeout=5) flash('Email is on the way to your mailbox.', 'primary') return redirect(url_for('sessions.new')) else: flash('Failed to send email. Please try again later.', 'danger') return redirect(url_for('sessions.new'))
def create_checkout(id): amt = float(request.form['amount']) result = transact({ 'amount': ("%.2f" % amt ), 'payment_method_nonce': request.form['payment_method_nonce'], 'options': { "submit_for_settlement": True } }) if result.is_success or result.transaction: image = Image.get_by_id(id) user = User.get_by_id(image.user) donation = Donation(donor=current_user.id,image=id,amount=result.transaction.amount) donation.save() q.enqueue_call(func=send_pay_email,args=(current_user,result.transaction.amount,),timeout=5) q.enqueue_call(func=send_pay_email,args=(user,result.transaction.amount,),timeout=5) return redirect(url_for('checkouts.show_checkout',transaction_id=result.transaction.id)) else: for x in result.errors.deep_errors: flash('Error: %s: %s' % (x.code, x.message)) return redirect(url_for('users.show'))
def classify_profile(self, results, database_to_include, sample, new_job_id, schemaVersion): job = q.enqueue_call(func=database_functions.classify_profile, args=( results, database_to_include, sample, new_job_id, schemaVersion, ), result_ttl=5000, timeout=600) return job.get_id()
def index(): form = InputForm() sessionJobInit() # can we avoid this? if form.validate_on_submit(): if app.debug: flash('Generating poem with title %s at drunkenness %s' %(form.titleSeed.data, str(form.howDrunk.data))) #return redirect('/') if session['job']: cancel_job(session['job'], connection=conn) job = q.enqueue_call(func=generate_text, args=(form.titleSeed.data,form.howDrunk.data),result_ttl=300, timeout=6000) session['job'] = job.get_id() print(job.get_id()) # e.g. 66df343f-2841-4fd2-986d-b83d459a6693 return render_template('reading.html', pageTitle=None, form=form, poemTitle=form.titleSeed.data, poemHowDrunk=str(form.howDrunk.data), poemContent='BIG ASS T**S', jobId = job.get_id()) return render_template('reading.html', pageTitle=None, form=form, putput='')
def etsy(): form = WoosyListingFromEtsyForm() if form.validate_on_submit(): etsy_url = form.etsy_url.data job = q.enqueue_call(func=create_woosy_listing_from_etsy, args=(etsy_url, ), timeout=5000) flash( Markup( f"Background task started: " f'<a href="/etsy/results/{job.get_id()}" class="alert-link">' f"{job.get_id()}" f"</a>!")) return redirect(url_for("etsy")) return render_template("listing_from_etsy.html", title="Etsy Sync", form=form)
def upload(): job_ids = [] if request.method == "POST": for key in request.files: with tempfile.NamedTemporaryFile( suffix=os.path.splitext(request.files[key].filename)[1], delete=False ) as temp: temp.write(request.files[key].stream.read()) temp.flush job = q.enqueue_call( func=ocr.extract_text, args=(request.files[key].filename, temp.name), result_ttl=5000 ) print(job.get_id()) job_ids.append(job.get_id()) return make_response(jsonify({"job_ids": job_ids}))
def register_user(): if not request.is_json: return jsonify({'msg': 'Missing or invalid JSON request '}) username = request.json.get('username', None) password = request.json.get('password', None) email = request.json.get('email', None) # Validate request if username and email and password: # Validate duplicate username / email user = User.query.filter_by(username=username).first() if user: return jsonify({'msg': 'Duplicate username'}) user = User.query.filter_by(email=email).first() if user: return jsonify({'msg': 'Duplicate email'}) # Hash password after passing validation hashed_password = bcrypt.generate_password_hash(password).decode( 'utf-8') job = q.enqueue_call(func=simulate_picture_upload, args=(username, hashed_password, email), result_ttl=10000) # new_user = User(username, hashed_password, email) # db.session.add(new_user) # db.session.commit() # return user_schema.jsonify(new_user) return jsonify( {'success': 'Profile is being created with id: ' + job.get_id()}) else: return jsonify({'msg': 'Missing fields'})
def start_packlist_index(): job = q.enqueue_call(func=tasks.index_packs) print str(job) return "Hello world"
def current_project(username, project_id): # Prevents users from accessing other's page. if current_user.id != User.query.filter_by(username=username).first().id: flash('You do not have access to this page!') return redirect(url_for('index')) # Query the database for tested sets. training = Training.query.filter_by(id=project_id).first() # Query the database for the users testing sets. all_testings = training.testing.all() # Adds all trainings to list for users to see each testing project. testings = [] for each in all_testings: testings.append({ 'id': each.id, 'project': each.project, 'ready': each.ready, 'filename': each.filename }) # Load the upload form. form = UploadTesting() # If the form is valid, submit the form. if form.validate_on_submit(): # Load data into f variable and description into d variable. f = form.upload.data d = form.description.data # Creates new testing entry for database. testing = Testing(project=d, user=current_user, training=training, ready=False) # Add and submit entry to database. db.session.add(testing) db.session.commit() # Query the database for this testing job. # This is to enable consistancy across input files, testing is added # to the database, then the id is obtained. testing_id = Testing.query.filter_by(user=current_user, project=d).first().id # Retrieves the filename for the input file. filename = secure_filename(f.filename) # Filenames are stored as "userid_trainingid_testingid_filename". filename = str(current_user.id) + '_' + str(project_id) + '_' + str( testing_id) + '_' + filename[:-4] # Save the file under instance/files/filename.csv. f.save(os.path.join(app.instance_path, 'files', filename + '.csv')) # Update the training database entry to include the new filename. testing.filename = filename # Merge and commit the entry to the database. db.session.merge(testing) db.session.commit() # Creates queue entry to process the uploaded data. # Calls the testing function for the worker. running_job = q.enqueue_call(func=testing_function, args=(testing_id, ), result_ttl=5000) # Flash the user and return to user/<username>/<currentproject> flash('File upload successful') return redirect( url_for('current_project', username=username, project_id=project_id)) # render user/<username>/<currentproject> return render_template('current_project.html', form=form, training=training.project, testings=testings)
new_value = random.uniform(v - 100, v + 10) if new_value > 0: stock.current_value = new_value stock.last_value = v sv = models.StockValues(stock_id=stock.id, value=stock.current_value) db.session.add(sv) print( str(stock.id) + ":" + str(v) + "/" + str(stock.current_value)) db.session.commit() time.sleep(7 * 60) return job = q.enqueue_call(func=update_stock, args=(), result_ttl=5000) @mod_site.route('/start_data') def start_data(): return jsonify(status="started") @mod_site.route('/list_companies_data') def list_companies_data(): """Return server side data.""" # defining columns columns = [ ColumnDT(models.Company.id), ColumnDT(models.Company.symbol), ColumnDT(models.Company.name + "|" + models.Company.name_ar),