예제 #1
0
def change_filters():

    """ It searches recipes by filters.

        Gets a lists of filters.

        Returns: list of recipes (list of objects)
                 list of cuisine (list of strings)
                 list of sources (list of strings)
                 list of categories (list of strings)
                 list of levels (list of strings
    """
    # Saves the parameters
    title = request.form("title")
    cuisine = request.form("cuisine")
    level = request.form("level")
    cat = request.form("cat")
    source = request.form("source")


    # Checks if the fields have a value and save them in a dictionary
    args = {}

    if title:
        args['title'] = title

    if cuisine:
        args['cuisine'] = cuisine

    if cat:
        args['cat_code'] = cat

    if level:
        args['skill_level'] = level

    if source:
        args['source'] = source
   
    # Calls the db functions to get lists of cuisine, sources, categories, titles
    cuisine = Recipe.getCuisineByFilter(**args)

    sources = Recipe.getSourcesByFilter(**args)

    categories = Recipe.getCatByFilter(**args)

    levels = Recipe.getLevelsByFilter(**args)

    titles = Recipe.getTitlesByFilter(**args)

    # Puts the data in a json format
    filters = {

       "cuisine": cuisine,
       "source" : sources,
       "categories": categories,
       "levels" : levels,
       "titles" : titles
    }

    return jsonify(filters)
예제 #2
0
def form_login():
    if request.method == 'POST':
        name = request.form('username')
        password = request.form('password')
    if request.method == 'GET':
        name = request.args.get('username')
        password = request.args.get('password')
    return redirect('/admin/')
예제 #3
0
def store_user_info():
    #print "VALUE : ",request.form
    uid = request.form("uid")
    token = request.form("token")
    first_name = request.form("first_name")
    last_name = reques.form("last_name")
    store_data.store_user_data(uid, token, first_name, last_name)
    return "Success"
예제 #4
0
파일: app.py 프로젝트: buddies2705/myapp
def main():
    if request.method=='GET':
        return render_template("main.html")
    elif request.method=='POST':
        qbAccessToken1=request.form('accessToken1')
        qbAccessToken2=request.form('accessToken2')
        if qbAccessToken1 is not None and qbAccessToken2 is not None:
            checkFordata(qbAccessToken1,qbAccessToken2)
예제 #5
0
def add_event(): 
	print '******************************'
	print "the form request", request.form
	hours = request.form('hours')
	print "the hours: ", hours
	subject = request.form('subject')
	print "the subject: ", subject
	user_id = session['user_id']
	print "the user_id: ", user_id
	sess = Session(hours=hours, subject_class=subject, user_id=user_id)
	db.session.add(sess)
	db.session.commit()

	flash("Awesome! We got down your hours!")
	return redirect('/')
예제 #6
0
def add_report():
    title = request.form("title")
    road = request.form("road")
    details = request.form("details")

    if not title:
        abort(400, "you must enter the report title")
    if not road:
        abort(400, "you must enter the accident road")
    if not details:
        abort(400, "you must enter the accident details")

    User(session["username"]).add_title(title, road, details)

    return redirect(url_for("index"))
예제 #7
0
파일: webapp.py 프로젝트: greyshi/ut-events
def submit():
    """TODO: submission form"""
    if request.method == 'POST':
        title = request.form('title')
        """Add row(s) to the database"""
    else:
        return render_template('submit.html')
예제 #8
0
def validate_config():
    json_response = {"errors": [], "valid": True}
    user_settings = {}

    # Extract config from POST
    if "config" in request.form:
        user_settings = json.loads(request.form("config"))

    # If the user did choose a language:
    if not user_settings.get("lang", None):
        json_response["valid"] = False
        json_response["errors"].append("Please select a language from the select box.")

    # If the user did not fill in the name option:
    if not user_settings.get("name", None):
        json_response["valid"] = False
        json_response["errors"].append("Please enter your name into the name box.")

    # Is a valid language set?
    if user_settings.get("language", None) in greetings:
        json_response["valid"] = False
        json_response["errors"].append(
            "We couldn't find the language you selected (%s) Please select another" % user_settings["language"]
        )

    response = make_response(json.dumps(json_response))
    response.mimetype = "application/json"
    return response
예제 #9
0
def logout():    
    if request.method == "GET":
        return render_template("logout.html")
    else:
        button = request.form("button") 
        if button == login:
            return redirect(url_for ("login"))
예제 #10
0
def finder():
  if request.method == 'POST':
    srch==request.form("_search")
  for e in f:
    x=e["level"]
    if x.__contains__(srch):
      f=e
예제 #11
0
	def post(self):

		user = flask.session['username']

		q=""" match (d:Diaries) return d.ID """
		resultl = gdb.query(q=q)

 
		if "btnmenusignout" in flask.request.form:
			flask.session.pop('username',None)
			return flask.redirect(flask.url_for('main'))

		if "submitsearch" in flask.request.form:
			flask.session['txtsearch'] = flask.request.form['txtsearch']
			return flask.redirect(flask.url_for('friendprofile'))
		
		Id = request.form('postid')
		txt = request.form('text')
예제 #12
0
파일: todo.py 프로젝트: KennF/Circus
def edit(id):
	todo = Todo.query.filter_by(id=id).first()
	form = TodoForm(title=todo.title)
	if request.method == 'POST' and form.validate_on_submit():
		Todo.query.filter_by(id=id).update({Todo.title: request.form('title')})
		db.session.commit()
		flash(u'记录编辑成功')
		return redirect(url_for('index'))
	return render_template('edit.html', todo=todo, form=form)
예제 #13
0
파일: api.py 프로젝트: wangxiaomo/SnipFlow
def update_snip(snip_id):
    snip = Snip.query.get(snip_id)

    if request.method == 'PUT':
        snip_context = request.form('snip_context')
        snip.snip_context = snip_context
        db.session.commit()
        return {'snip_id':snip.id, 'snip_context':snip.context}
    else:
        db.session.delete(snip)
        db.session.commit()
        return {'snip_id':snip.id}
예제 #14
0
def get_facebook_friends():
    """ from a facebook short lived token returns a long lived token to the client (we need to catch the http errors..."""

    short_lived_token = request.form('short_lived_token')
    app_id = request.form['app_id']
    app_secret = request.form['app_secret']
    url = 'https://graph.facebook.com/oauth/access_token'+ '?grant_type=fb_exchange_token&client_id='+ app_id+ '&client_secret='+ app_secret+ '&fb_exchange_token='+ short_lived_token
    
    long_lived_token = urllib2.urlopen(url).read()
    if 'access_token=' in long_lived_token:
        long_lived_token = long_lived_token.replace('access_token', '')

    return long_lived_token
예제 #15
0
def handle_single_tweet(id):
  for tweet in tweets:
    if tweet['id'] == id:
      if request.method == 'GET':
        return jsonify(tweet)
      elif request.method == 'PUT':
        tweet['text'] = request.form('text')
        return jsonify(tweet)
      else:
        removed = tweet
        tweets.remove(tweet)
        return jsonify(removed)
  return jsonify({"error": "Not found"})
예제 #16
0
def show_login():
    """Show login form."""
    if request.method == 'POST':
        email = request.form('email')
        password = request.form('password')


        session['email'] = request.form['email']
        session['password'] = request.form['password']

        # print email
        # print password

        return redirect(url_for('index'))
   
    if request.method == "GET":

        email = request.args.get('email')
        password = request.args.get('password')
        return render_template("login.html")
        
        print email
        print password 
예제 #17
0
def index():
	'''renders the index template, shows stored notes, and allows new notes to be added'''
	if request.method == "POST":
		try:
			noteName = request.form("noteName")
			note = request.form("note")
			insert = notes.insert()
			insert.execute(noteName = noteName, note = note)
			selectName = notes.select(notes.noteName)
			selectNote = notes.select(notes.note)
			selExNa = selectName.execute()
			selExNo = selectNote.execute()
			oldNotes = {selExNa : selExNo}
			return render_template("index.html", oldNotes = oldNotes)
		except Exception as e:
			selectName = notes.select(notes.noteName)
			selectNote = notes.select(notes.note)
			selExNa = selectName.execute()
			selExNo = selectNote.execute()
			oldNotes = {selExNa : selExNo}
			return render_template("index.html", e = e, oldNotes = oldNotes)
	elif request.method == "GET":
		return render_template("index.html")
예제 #18
0
def register():
    error = None
    if request.method == 'POST':
        if create_user(username=request.form['username'],
                       password=request.form['password'],
                       confirmation=request.form['confirm_pass'],
                        firstName=request.form['first_name'],
                        lastName=request.form['last_name'],
                        email=request.form('email'),
                       dbclient=myclient):
            return 'hello'
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
예제 #19
0
def artview():

    #show list of all songs and albums by an artist
    if request.method = 'POST':
        artist = request.form('artist')

        error = 0
        if not artist:
            error = 'Please enter an artist'

        #get table of songs and corresponding albums by artist
        cursor = g.conn.execute("SELECT song_name, album_name, song.published_date
                                FROM artist, perform, song, contains, album
                                WHERE artist.artist_id = perform.artist_id AND song.song_id = perform.song_id
                                AND song.song_id = containst.song_id AND album.album_id = contains.album_id
                                AND artist.artist_name = (%s)", artist)
        
        artistres = cursor.fetchall()
        cursor.close
        
        if not artistres:
            error = 'No results'

        #get table of musicians who are members of the artist
        cursor = g.conn.execute("SELECT musician_name, role, artist_name
                                FROM artist AS ar, member_of AS m, musician AS mu
                                WHERE ar.artist_id = m.artist_id AND m.musician_id = mu.musician_id
                                AND ar.artist_name = (%s)", artist)

        for result in cursor:
            musicians.append(result[0], result[1], result[2])
        cursor.close()

        musicians = cursor.fetchall()
        cursor.close()
        
        error2 = 0
        if not musicians:
            error2 = 'No musicians listed'

        if error:
            flash(error)

        if error2:
            flash(error2)

        return render_template("artview.html", artistres = artistres, musicians = musicians)
예제 #20
0
def incidencia():
    
    
    #Validar que los valores de los casos sean números y sean enteros positivos
    #estudiar objeto request de la libreria
    #vslorar num_casos_prueba_pcr >= 0 y entero
    formulario = {
        'provincia': '',
        'fecha': str(date.today()),
        'num_casos_prueba_pcr': 0,
        'num_casos_prueba_test_ac': 0, 
        'num_casos_prueba_ag': 0,
        'num_casos_prueba_elisa': 0,
        'num_casos_prueba_desconocida': 0
    }

    fichero = open ('data/provincias.csv', 'r')
    csvreader = csv.reader (fichero, delimiter =',') #ocupamos el metodo csv para delimitar la estructura ','
    next(csvreader)
    lista = []
    for registro in csvreader:
        d = {'codigo':registro[0], 'descripcion' : registro[1]}
        lista.append (d)

    fichero.close()

    if request.method == 'GET':
        return render_template("alta.html", datos=formulario, 
                               provincias=lista, error="")
    
    #validar que num_casos en general no es negativo

    for clave in formulario:
        formulario[clave] = request.form [clave]


    num_pcr = request.form ('num_casos_prueba_pcr')
    try:
        num_pcr = int (num_pcr)
        if num_pcr < 0:
            raise ValueError ('Debe ser no negativo')

    except ValueError:
        return render_template("alta.html", datos=formulario, error = "PCR no puede ser negativa")
    
    return "Se ha hecho un post"
예제 #21
0
def result():
    if request.method == "POST":
        return render_template(
            "submitinfo.html", 
            name = request.form["name"],
            location = request.form["location"],
            fav_language = request.form["favorite_language"],
            comment = request.form["comment"]
        )
    else:
        return render_template(
            "submitinfo.html",
            name = request.args.get("name"),
            location = request.args.get("location"),
            fav_language = request.args.get("favorite_language"),
            comment = request.form("comment")
        )
예제 #22
0
def process_login():
    # Get the request object and the parameters sent.
    firstname = request.form['firstname']
    surname = request.form['surname']
    nationalidentificationnumber = request.form('nationalidentificationnumber')

    # call our custom defined function to authenticate user
    if (authenticateUser(firstname, surname, nationalidentificationnumber)):
        session['username'] = firstname
        session[
            'userroles'] = 'admin'  # just hardcoding for the sake of illustration. This should be read from database.
        return redirect(session['next_url'])
    else:
        error = 'Invalid user or password'
        return render_template('login.html',
                               title="SIGN IN",
                               information=error)
예제 #23
0
def home():
    if request.method == 'POST':
        if request.form('button') == 'logout':
            logout()


##    if 'remote_oauth' in session:
##        resp = remote.get('me')
##        return jsonify(resp.data)
##    next_url = request.args.get('next') or request.referrer or None
##    return remote.authorize(
##        callback=url_for('authorized', next=next_url, _external=True)
##    ) and render_template('home.html')
    if 'remote_oauth' in session:
        resp = remote.get('me')
        return jsonify(resp.data)
    return render_template('home.html')
예제 #24
0
def predict():
    if request.method == 'POST':
        sentence = request.form("text")

        prediction = sentence_prediction(sentence)
        movie_df = pd.read_csv("/inputs/movies.csv")
        similarity = cosine_similarity(prediction, movie_df[['anger', 'disgust', 'fear', 'joy', 'sadness', 'surprise']].values)
        movie_df['similarity'] = similarity[0]
        result = movie_df.sort_values(by=['similarity', 'avg_vote', 'year'], ascending=False).head(10)

        m1 = result.loc[0 , 'original_title']
        m2 = result.loc[1 , 'original_title']
        m3 = result.loc[2 , 'original_title']
        m4 = result.loc[3 , 'original_title']
        m5 = result.loc[4 , 'original_title']

    return render_template('results.html', movie_1 = m1, movie_2 = m2, movie_3 = m3, movie_4 = m4, movie_5 = m5 )
예제 #25
0
파일: app.py 프로젝트: pigHuman/TRPG
def charSelect():
    char = []
    username = session["username"]
    char_data = mongo.db.charsheet.find({"username": username})

    for i in char_data:
        char.append(i['characterName'])

    print(char)

    return render_template('charSelect.html', char=char)

    if request.method == 'POST':
        charName = request.form("charName")
        charData = charsheet_find(charName)
        print(charData)
        return jsonify(ResultSet=charData)
예제 #26
0
파일: api.py 프로젝트: ruizhe-w/Book-Bridge
def get_image():
  if request.method == 'POST':
    user_ID = request.form('User_Id')

    db = get_db()

    cursor = db.cursor()

    cursor.execute(
      "SELECT userImage from UserTable where USER_ID = {}".format(user_ID)
    )

    result = cursor.fetchall()

    return make_response(result)

  raise Exception()
예제 #27
0
def register_user():
    # data validation
    #var to check if anny errors have been thrown
    validation_error = True

    if not REGEX_NAME.match(request.form['first_name']):
        flash('First name may only contain letters', 'error')
        validation_error = False
    if not REGEX_NAME.match(request.form['last_name']):
        flash('Last name may only contain letters', 'error')
        validation_error = False
    if not REGEX_EMAIL.match(request.form['email']):
        flash('Please enter a valid email address.', 'error')
        validation_error = False
    if not REGEX_PASS.match(request.form['pass1']):
        flash('Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.', 'error')
        validation_error = False
    if not request.form['pass1'] == request.form['pass2']:
        flash('Passwords must match.', 'error')
        validation_error = False

    if validation_error == False:
        return redirect('/')

    query = "SELECT id FROM users WHERE email = '{}'".format(request.form['email'])
    userid = mysql.query_db(query)

    if len(userid)>0:
        flash('That email is already in use. Please use the login form.', 'error')
        return redirect('/')

    query = 'INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES (:fname, :lname, :email, :pw_hash, NOW(), NOW())'
    data = {
        'fname': request.form['first_name'],
        'lname': request.form['last_name'],
        'email': request.form['email'],
        'pw_hash': bcrypt.generate_password_hash(request.form['pass1'])
    }
    mysql.query_db(query, data)

    #set session id so the user is auto logged in
    query = 'SELECT id FROM users WHERE email = "{}"'.format(request.form['email'])
    uid = mysql.query_db(query)
    session['id'] = request.form(['email'])
    return redirect('/success')
예제 #28
0
def assignment():
    if request.method == "GET":
        course_id = request.args.get('Courseid')
        coursedata = Course.query.filter_by(course_id=course_id).first()
        data = db.session.query(
            Course.id, Course.course_name, Assignment.id,
            Assignment.assignment_name, Assignment.assignment_grade,
            Assignment.assignment_startdate,
            Assignment.assignment_duedate).join(
                Course, Course.id == Assignment.courses).filter(
                    Course.course_id == course_id).order_by(Course.id).all()
        recordcount = Assignment.query.filter_by(courses=coursedata.id).count()
        return render_template("assignment.html",
                               timestamp=datetime.now(),
                               title='Assignment Details',
                               course_id=course_id,
                               AssignmentDetails=data,
                               course_name=coursedata,
                               recordcount=recordcount)

    if request.method == "POST":
        course_id = request.form('Courseid')
        coursedata = Course.query.filter_by(course_id=course_id).first()
        recordcount = Assignment.query.filter_by(courses=coursedata.id).count()
        data = db.session.query(
            Course.id, Course.course_name, Assignment.id,
            Assignment.assignment_name, Assignment.assignment_grade,
            Assignment.assignment_startdate,
            Assignment.assignment_duedate).join(
                Course, Course.id == Assignment.courses).filter(
                    Course.course_id == course_id).order_by(Course.id).all()
        return render_template("assignment.html",
                               timestamp=datetime.now(),
                               title='Assignment Details',
                               course_id=course_id,
                               AssignmentDetails=data,
                               course_name=coursedata,
                               recordcount=recordcount)
    else:
        return redirect(url_for('assignment'))

    if not current_user.is_authenticated:
        return render_template("login_page.html", error=True)

    return redirect(url_for('assignment'))
예제 #29
0
def predict():
    Fuel_Type_Diesel = 0
    if request == "POST":
        
        Year = int(request.form['year'])
        
        present_price = float(request.form("present_price"))
        
        Kms_Driven = float(request.form(['Kms_Driven']))
        
        Owner = int(request.form(['Owner']))
        
        Fuel_Type_Petrol = request.form(['Fuel_Type_Petrol'])
        if(Fuel_Type_Petrol == "Petrol"):
            Fuel_Type_Petrol = 1
            Fuel_Type_Diesel = 0
        else:
            Fuel_Type_Petrol = 0
            Fuel_Type_Diesel = 1
            
        Seller_Type_Individual = request.form(['Seller_Type_Individual'])
        if(Seller_Type_Individual == "Individaul"):
            Seller_Type_Individual = 1
        else: 
            Seller_Type_Individual = 0
            
        Transmission_Mannual = request.form(['Transmission_Mannual'])
        if(Transmission_Mannual == "Mannual"):
            Transmission_Mannual = 1
        else:
            Transmission_Mannual = 0
            
        prediction=model.predict([[Present_Price,
                                   Kms_Driven2,
                                   Owner,
                                   Year,
                                   Fuel_Type_Diesel,
                                   Fuel_Type_Petrol,
                                   Seller_Type_Individual,
                                   Transmission_Mannual
                                   ]])
                
        output=round(prediction[0],2)
        
        if output<0:
            return render_template('index.html',prediction_texts="Sorry you cannot sell this car")
        else:
            return render_template('index.html',prediction_text="You Can Sell The Car at {}".format(output))
        
    else:
        return render_template('index.html')
예제 #30
0
파일: api.py 프로젝트: ruizhe-w/Book-Bridge
def get_book_recommendation():
  if request.method == 'POST':
    user_ID = request.form('User_Id')

    p = boto3.client('personalize-runtime')

    response = p.get_recommendations(
      campaignArn = 'arn:aws:personalize:us-east-2:529652464554:campaign/generated-data-campaign',
      userId = user_ID)

    return make_response(response['itemList'])

  p = boto3.client('personalize-runtime')

  response = p.get_recommendations(
     campaignArn = 'arn:aws:personalize:us-east-2:529652464554:campaign/generated-data-campaign',
      userId = '9993994435782955')

  return make_response(response['itemList'])
예제 #31
0
def submitFarmer():
    """
    Endpoint to create a new transaction via our application.
    """
    post_content = request.form["content"]
    farmer_ID = request.form["farmer_ID"]
    field3 = request.form('field3')

    post_object = {
        'Farmer_ID': farmer_ID,
        'content': post_content,
    }

    new_tx_address = "{}/new_transaction".format(CONNECTED_NODE_ADDRESS)
    requests.post(new_tx_address,
                  json=post_object,
                  headers={'Content-type': 'application/json'})

    return redirect('/')
예제 #32
0
def edit_course(category_id, course_id):
    try:
        course = session.query(Course).filter_by(
            id=course_id, category_id=category_id).one()
    except:
        return error_message(404, "Cannot update: Course not found.")
    if request.form.get(
            'name'
    ):  # if 'name' is a non-empty value then update else keep current value
        course.name = request.form('name')

    course.description = request.form.get('description')
    course.img_url = request.form.get('img-url')
    course.intro_video_url = request.form.get('intro-video-url')

    session.add(course)
    session.commit()
    return data_message(200, {"Course": course.serialize},
                        "Successfully updated the course.")
예제 #33
0
def upload_file():
	#If user isn't signed in, redirect
	if(session["username"] == ""):
		return redirect(url_for("login"))

	#Get tags
	if(request.method == "POST"):
		tags = request.form("tags")
		tags = tags.split(",")

	target = os.path.join(UPLOAD_FOLDER, "static/")

	if not os.path.isdir(target):
    	os.mkdir(target)

  	for upload in request.files.getlist("file"):
  		filename = upload.filename
    	#Add the picname and return the id
    	cur.execute("INSERT INTO pictures (picname, username) VALUES (%s, %s) RETURNING picid;", [filename, session["username"]])
    	id = cur.fetchone()
    	conn.commit()

    	#For every tag insert with picid
    	for tag in tags:
    		cur.execute("INSERT INTO tags (picid, tag) VALUES (%s, %s);", [id, tag])
    	conn.commit()

    	#Save image
    	destination = "/".join([target,filename])
    	upload.save(destination)

	return render_template("ImageDisplay.html", image_name = filename)

#Location of the image
@app.route("/upload/<filename>")
def send_image(filename):
  return send_from_directory("static",filename)

if __name__ == "__main__":
	#Key used for encrypting session data
	app.secret_key = os.urandom(24)
	app.run()
예제 #34
0
def capture_email():
	success = False
	errors = {}
	if request.method == "POST" and 'honeypot' in request.form and len(request.form['honeypot']) < 1 and 'email' in request.form:
		if 'email' in request.form and len(request.form['email'])>0:
			session['email'] = request.form['email']
			if len(request.form['name'])>0 and session['name'] is not None and request.form['name'].upper() == session['name'].upper():
				user = User.query.filter_by(name=session['name']).first()
				user.email = request.form('email')
			else:
				create_user(request.form['email'],request.form['name'])
			save_answer()
			sub = Subscriber()
			sub.add(campaign_monitor_list_id,request.form['email'],request.form['name'],[],True)
			success = True
		else:
			errors['email'] = 'we need an email to keep in touch'
	if request.method == "POST" and 'ajax' in request.form:
		return render_template('email_question.html',success=success,form=request.form,errors={})
	update_session_question('email',{'success':success,'errors':errors})
	return redirect("/#email_question")
예제 #35
0
def update_recipe(recipe_id):
    recipes = mongo.db.recipes
    recipes.updateOne({'_id': ObjectId(recipe_id)},
                      {
        'country_name': request.form.get('country_name'),
        'course_type': request.form.get('course_type'),
        'recipe_name': request.form.get('recipe_name'),
        'user_name': request.form.get('user_name'),
        'recipe_description': request.form.get('recipe_description'),
        'preparation_time': request.form.get('preparation_time'),
        'cooking_time': request.form.get('cooking_time'),
        'total_time': request.form.get('total_time'),
        'servings': request.form.get('servings'),
        'ingredients': request.form.get('ingredients'),
        'instructions': request.form.get('instructions'),
        'allergens': request.form.get('allergens'),
        'tags': request.form.get('tags'),
        'recipe_creator': request.form.get('recipe_creator'),
        'img_url': request.form('img_url')
    })
    return redirect(url_for('get_recipes'))
예제 #36
0
def taxes():
    try:
        form=nationalityform(request.form)
        if request.method=='POST' and form.validate_on_submit():
            nationality=request.form('nationality')
            passport_number=request.form('passport_number')
            visa_type=request.form('visa_type')
            date_of_entry=request.form('date_of_entry')
            travel_boolean=request.form('travel_boolean')
            visa_change=request.form('visa_change')



        return render_template('Nationality.html', form=form)
    except Exception as e:
        return (str(e));
예제 #37
0
파일: home.py 프로젝트: Shofia0324/Foodie
def process_registration():
    error = None
    if request.method == 'GET/POST' :
        username = request.form("username"),
        email = request.form("email"),
        password = request.form("password"),
        phone = request.form("phone"),
        bn = request.form("bn"),
        street = request.form("street"),
        area = request.form("area"),
        pin = request.form("pin"),
        #addObj = Address(bn,street,area,pin)
        #custObj = Customers(username, email, password, phone, addObj)
        #data.customers[custObj.getUsername()] = custObj
        user = data.customers(username = username, email = email, password = password, phone = phone, bn = bn, street = street, area = area, pin = pin )
        listCustomers.append(user)
        custDB = Service.saveCust()
        if user == custDB:
            flash('You are successfully registered')
        else :
            flash('Error occured')
        return redirect(url_for('/home'))
    return render_template('registration.html', error = error)
예제 #38
0
def judge_search():

    display = request.form('autocomp')
    conn = sqlite3.connect('defatty_stats_real.sqlite')
    c = conn.cursor()
    # request.form['judge_statute_text']
    # Gets the total cases for that statute for that atty
    judge_statute_totals = c.execute("SELECT atty_total FROM defatty_stats WHERE atty=? and statute=?",
                                     (display, request.form['judge_statute_text'], )).fetchall()
    # Displays the atty name
    judge_name = c.execute("SELECT atty FROM defatty_stats WHERE atty=?",
                           (display, request.form['judge_text'])).fetchone()
    # Displays the statute
    judge_statute = c.execute("SELECT statute FROM defatty_stats WHERE statute=?",
                              (request.form['judge_statute_text'], )).fetchone()

    return render_template('judge.html',
                           judge_name=judge_name,
                           judge_statute_totals=judge_statute_totals,
                           judge_statute=judge_statute,
                           display=display
                           )
예제 #39
0
def login_now():
    print("hello")
    print(request.form())
    name1 = request.form['username']
    print(name1)
    if reg.find_one({"name": name1}) == 'None':
        return "User Does Not Exist"
    else:
        if request.form['user-type'] == Authority:
            user_det = reg.find_one({'name': request.form['username']})
            if user_det['password'] == request.form['password']:

                return render_template("authority.html", naam=name1)
            else:
                return render_template("login.html", naam="Invalid Password")
        else:
            user_det = reg.find_one({'name': request.form['username']})
            if user_det['password'] == request.form['password']:

                return render_template("index2.html", naam=name1)
            else:
                return render_template("login.html", naam="Invalid Password")
예제 #40
0
파일: app.py 프로젝트: m16shoukry/FSND
def create_venue_submission(): 
  form = request.form()
  name = request.form['name']
  city = request.form['city']
  state = request.form['state']
  address = request.form['address']
  phone = request.form['phone']
  genres = request.form['genres']
  facebook_link = request.form['facebook_link']
  try:
    venue = Venue( 
                name=name,
                city=city,
                state=state,
                address=address,
                phone=phone,
                genres=genres,
                facebook_link=facebook_link
                ) 
    db.session.add(venue)
    db.session.commit()  
    flash('Venue ' + request.form['name'] + ' was successfully listed!')
예제 #41
0
def login():
    if request.method == 'GET':
        referrer = request.args.get('login', '/')
        return render_template("login.html", next=referrer)
    if request.method == 'POST':
        u = request.form.get('username')
        p = request.form.get('password')
        n = request.form('login')
        try:
            g.db.cursor.execute('SELECT name FROM users WHERE name = %s',
                                (u, ))
            if not g.db.cursor.fetchone():
                raise loginError(u'错误的用户名或者密码!')
            g.db.cursor.execute(
                'SELECT salt,password FROM users WHERE name = %s', (u, ))
            password = g.db.cursor.fetchone()
            if password == password:
                session['logged_in'] = u
                return redirect(url_for('show_info'))
            else:
                raise loginError(u'错误的用户名或者密码!')
        except loginError as e:
            return render_template('login.html', next=next, error=e.value)
예제 #42
0
    def get_address_info():
        # 获取系统当前的基本信息
        if request.method == 'POST':
            address = request.form('address')
            print(address)

        else:
            print('get')
            address = request.args.get('address')
            get_usr_account_result = get_usr_account(address)

            response = {
                'address': get_usr_account_result['_id'],
                'token': get_usr_account_result['token'],
                'usdt': get_usr_account_result['usdt'],
                'share': get_usr_account_result['share'],
                'contract': get_usr_account_result['contract'],
                'nonce': get_usr_account_result['nonce'],
                'birth_time': get_usr_account_result['birth_time'],
                'hash': get_usr_account_result['hash']
            }
            print(type(response))
            return jsonify(response), 200
예제 #43
0
def login():
    if (request.method == 'POST'):
        username = request.form['username']
        password = request.form('password')
        db = get_db()
        error = None

        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password/'

        if error is None:
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/log-in.html')
예제 #44
0
def index_page():
    prediction = ""
    if request.method == "POST":
        att0 = request.form("att0", "")
        att1 = request.form("att1", "")
        att2 = request.form("att2", "")
        att3 = request.form("att3", "")
        att4 = request.form("att4", "")
        att5 = request.form("att5", "")

        att2 = int(att2)
        att5 = int(att5)

        prediction = predict_interviews_well(
            [att0, att1, att2, att3, att4, att5])

    # goes into templates folder and finds given name
    return render_template("index.html", prediction=prediction)
예제 #45
0
파일: app.py 프로젝트: sumantopal07/FLyrr
def edit_venue_submission(venue_id):
    error = False
    try:
        #venue = Venue(name=request.form['name'],city=request.form['city'],state=request.form['state'],address=request.form['address'],phone=request.form('phone'),genres=request.form['genres'],facebook_link=request.form['facebook_link'])
        x = Venue.query.filter_by(id=venue_id).first()
        x.name = request.form['name']
        x.city = request.form['city']
        x.state = request.form['state']
        x.address = request.form['address']
        x.phone = request.form('phone')
        x.genres = request.form['genres']
        x.facebook_link = request.form['facebook_link']
        x.image_link = request.form['image_link']
        db.session.commit()
    except:
        error = True
        db.session.rollback()
    finally:
        db.session.close()
    if error:
        abort(400)
    else:
        flash('Venue ' + request.form['name'] + ' was edited successfully!')
    return redirect(url_for('show_venue', venue_id=venue_id))
예제 #46
0
def form():
    """
    Renders the results page. While the program is running, if a user
    submits/enters a dropdown menu selection, then enters the submission.
    This function activates and sends the info stored in the 'posts' variable
    to the ResultsPage.html.
    :return:
    """
    if request.method == 'POST':
        query = request.form('query')
    else:
        query = request.args.get('query')

    if query is None:
        print("You changed the name of the select list! Change it back to query.")

    posts = sheet.convertToDict(sheet[query])

    if len(posts) > 0:
        query = [item for item in sheet['query'] if item != '']
        pair = list(zip(sheet.textLength(query, 50), query))
        return render_template("ResultsPage.html", posts=posts, pair=pair)
    else:
        return render_template("ResultsPage.html")
예제 #47
0
def login():
    if request.method == 'POST':
        #Get Form Fields
        username = request.form('username')
        password_candidate = request.form['password']

        # Create cursor
        cur = mysql.connection.cursor()

        #Get user by username
        result = cur.execute("SELECT * FROM users WHERE username = %s",
                             [username])

        if result > 0:
            #get stored hash

            data = cur.fetchone()
            password = data['password']

            if sha256_crypt.verify(password_candidate, password):

                session['logged_in'] = True
                session['username'] = username

                flash('You are now logged in', 'success')
                return redirect(url_for('dashboard'))
        else:
            error = 'Invalid login'
            return render_template('login.html', error=error)
        #Close connection
        cur.close()
    else:
        error = 'Username not found'
        return render_template('login.html', error=error)

    return render_template('login.html')
예제 #48
0
def reports(id):
    form = ReportForm(request.form)
    user_id = id
    cursor = mysql.connection.cursor()
    type = cursor.execute('select user_type from users where user_id = %s',
                          [user_id])
    cursor.close()
    if type == 'customer':
        if request.method == "POST" and form.validate():
            customer_id = request.form('customer_id')
            manager_id = request.form('manager_id')
            restaurant_name = request.form('restaurant_name')
            restaurant_id = request.form('restaurant_id')
            review = request.form('review')
            rating = request.form('rating')
            cursor.execute(
                'INSERT INTO reports(customer_id,restaurant_name, review, rating, restaurant_id)VALUES(%s, %s, %s, %s, %s)',
                (id, restaurant_name, review, rating, restaurant_id))
            cursor.execute(
                'select manager_id from restaurant_manager where restaurant_id = %s',
                [restaurant_id])
            manager = cursor.fetchone()
            cursor.execute('INSERT INTO reports(manager_id) VALUES(%s)',
                           [manager])
            mysql.connection.commit()
            cursor.close()
            flash('Report successfully added')
            return redirect(url_for('user_dashboard'))
        cursor = mysql.connection.cursor()
        cursor.execute('select * from reports where customer_id = %s',
                       [user_id])
        report = cursor.fetchall()
        cursor.close()
    else:
        cursor = mysql.connection.cursor()
        cursor.execute('select * from reports where manager_id = %s',
                       [user_id])
    return render_template('REPORTS.html',
                           reports=reports,
                           form=form,
                           type=type)
예제 #49
0
def register():
	render=request.form()
	return render[0]
예제 #50
0
def api_page_mutate(page_entryid):
    """
    Primary page mutation interface

    """

    COMMIT_ATTEMPTS = 30 # otherwise something is pretty wrong!
    
    
    action = request.form('action')
    page_ver_id = request.form('page_ver_id')

    for commit_attempt in range(COMMIT_ATTEMPTS):

        latest_page_entry_doc = db_get_entry_doc(page_entryid)

        if str(latest_page_entry_doc.head) != page_ver_id:
            print "Page has been updated since this edit"


        latest_page_rev_doc  = g.db.dereference(latest_page_entry_doc.head)

        if can_mutate_page(action, latest_page_rev_doc,
                      action_data) :
            new_doc = mutate_page(action, latest_page_rev_doc,
                                  action_data)
            author = bson.dbref.DBRef(session["user_id"], "users")

            new_doc.update(dm.revision_create(author,
                                              parent=latest_page_rev))
            
            new_doc_oid = revisions.insert(new_doc, safe=True)

            # create new, updated entry doc pointing to this doc

            new_entry_doc = d.entry_create(bson.dbref.DBRef(new_doc_oid,  'revisions'),
                                           latest_page_entry_doc['class'])

            # compare-and-swap
            res = entries.update(latest_page_entry_doc,
                                 new_entry_doc, safe=True)
            
            if res['updatedExisting'] == True:
                # success!
                return jsonify({"latest_page_revision_doc" : new_doc})
                              
            
            else:
                # failed to update, meaning someone else updated the entry ahead of us
                revisions.remove({'_id' : new_doc_oid})
                
                # then loop

        else:
            # couldn't actually perform mutation,
            # return latst doc along with status "Invalid mutation"
            
            return jsonify({"reason" : "invalid mutation" ,
                            "latest_page_revision_doc" : latest_page_rev_doc}), 400

        return jsonify({"reason" : "too much contention"}), 400
예제 #51
0
def rate(email, name):
    members = utils.userGroupMembers(email)
    ratings = utils.get_response(email)
    return render_template("rate.html", name = name, members = members, ratings=ratings)
    if (request.form(buttonvalue == "Submit")):
        return confirm()
예제 #52
0
def rate():
   
   if session.get('username'):
      #if request.method == 'POST':
      try:
         email
      except NameError:
         return redirect(url_for('logout'))

      info = datastorage.getData(email)

      projects = []
      count = 1
      while(count <= len(info)):
         projects.append(datastorage.getGroupMembers(email,str(count)))
         count = count + 1




      numratings = 0
      sumratings = 0
      scores = []
      for projs in info:
        for ratings in projs:
            numratings = numratings + 1
     #       sumratings = sumratings + info[projs][ratings]['score']
     #       scores.append(info[projs][ratings]['score'])
      avgrating = datastorage.getAvgOverallIndividualPoints(email)

      stdev = 0
      if numratings != 0:
         ex = 0
         for score in scores:
            ex = ex + (score-avgrating) * (score-avgrating)
         stdev = math.sqrt(ex/numratings)

      first = datastorage.getFirst(email)
      last = datastorage.getLast(email)



      questionavgs=[]
      
      for x in range(len(questions)):
         r=0
         for i in range(len(info)):
            r=r+datastorage.getTotalIndividualAvgForQuestion(email,x)#(email,i+1,questions[x])
            questionavgs.append(r/len(info))
      loggedin=True
         

         
      if request.method == 'POST':
         
         rater = email
         ratee = request.form('ratees')
         num = 0
         for n in questions:
            datastorage.ratePerson(rater=rater, ratee=ratee,question=n,score=request.form(n),comments=None)
     # rating1 = request.form('question1')
     # rating2 = request.form('question2')
     # rating3 = request.form('question3')
      
     # datastorage.ratePerson(rater=rater, ratee=ratee,question=questions[1],score=rating1,comments=None)
     # datastorage.ratePerson(rater=rater, ratee=ratee,question=questions[2],score=rating2,comments=None)

     # datastorage.ratePerson(rater=rater, ratee=ratee,question=questions[3],score=rating2,comments=None)
         

      return render_template('index.html',loggedin=True,projects=projects,questions=questions,avgrating=avgrating,stdev=stdev,questionavgs=questionavgs)
예제 #53
0
def redirect():
	if request.method == 'POST':
		if request.form('search' ,None) == "Like":
			return redirect(url_for('bc.html'))
		elif request.form('search',None) == "Dislike":
			return redirect(url_for('bc.html'))
예제 #54
0
def mafia_mkroom():
	room = request.form('mkRoom_name')
	return render_template("game/mafia/index.html", activity='mafia')
예제 #55
0
파일: api.py 프로젝트: wangxiaomo/SnipFlow
def create_snip():
    snip_context = request.form('snip_context')
    snip = Snip(snip_context)
    db.session.add(snip)
    db.session.commit()
    return {'snip_id':snip.id, 'snip_context':snip.context}
예제 #56
0
def submit_form_post():
	name = request.form('name')
	age = request.form('age')
	ninja = request.form('FavNinja')
	return render_template('index.html', name=name, age=age, ninja='Patrick Huston')
예제 #57
0
파일: server.py 프로젝트: pranavrc/radar
def index():
    if request.method == 'GET':
        return render_template('index.html')
    if request.method == 'POST':
        print request.form('position');