Beispiel #1
0
def add_user_class(class_id):
  lst = ls_path('home')
  ls_std = ls_path('tutor')
  if not current_user.id == Classe.query.filter_by(id=class_id).first().tutor_id:
    return render_template('errors_page/unauthorized.html',
      title='unauthorized',
      files=lst,
      Course=Course,
      url=url,
      get_admin=get_admin,
      get_tutor=get_tutor, 
      get_student=get_student)
  form = MyForm()
  if form.validate_on_submit():
    user = User.query.filter_by(email=form.autocplt.data).first().id
    add_user = Enrolled(user_id=user, classe_id=class_id)
    db.session.add(add_user)
    db.session.commit()
    flash('Congratulations, user Enrolled into a Class!')
    return redirect('/classes/%s/add_user_class' % class_id)
  return render_template('classes/add_user_class.html', 
    title='classe %s' % (class_id), 
    files=lst,
    Course=Course,
    User=User,
    Enrolled=Enrolled,
    fbase=ls_std, 
    class_id=class_id,
    url=url, 
    form=form, 
    get_classe_name=get_classe_name,
    get_admin=get_admin, 
    get_tutor=get_tutor, 
    get_student=get_student )
Beispiel #2
0
def upload():    
    form = MyForm()
    if form.validate_on_submit ():  
        start_time = time.time()
        _, file_ext = os.path.splitext(form.file.data.filename)
        files_dir= os.path.join(os.getcwd(), 'files')
        html_dir = os.path.join(files_dir, 'html_results')
        fname=secrets.token_hex(nbytes=16)+file_ext
        filename=os.path.join(files_dir, fname)
        if 'files' not in os.listdir(os.getcwd()):
            os.mkdir(files_dir)
        if not os.path.exists(html_dir):
            os.mkdir(html_dir)
        prepeare_time = time.time()-start_time
        form.file.data.save(filename)
        f=open(filename,'r', encoding=detectEncoding(filename)['encoding'])
        open_time = time.time()-prepeare_time
        result=count_letters_RU(f.read())
        f.close()
        count_time = time.time() - open_time
        letters=list(result.keys())
        values=list(result.values())
        fig = go.Figure([go.Bar(x=letters, y=values)])
        py.offline.plot(fig, filename=os.path.join(html_dir, fname)+'.html' , auto_open=True)
        graph_time = time.time() - count_time
        print (f'Время подготовки %d c, время открытия файла %d c, \
                время подсчета %d c, время построения графика %d c' %\
                (prepeare_time, open_time, count_time, graph_time))
        return render_template('index.html',title = form.name.data)
    return render_template('upload.html', form=form)
Beispiel #3
0
def contact():
    """Render the website's contact page."""
    form = MyForm()
    if form.validate_on_submit():
        msg = Message(request.form['subject'],
                      sender=(request.form['name'], request.form['email']),
                      recipients=["*****@*****.**"])
        msg.body = request.form['message']
        mail.send(msg)
        flash('Form successfully sent.')
        return redirect('/')
    return render_template('contact.html', form=form)
Beispiel #4
0
def upload():
    print('enter upload')
    form = MyForm()
    if form.validate_on_submit():
        _, file_ext = os.path.splitext(form.file.data.filename)
        files_dir = os.path.join(os.getcwd(), 'files')
        filename = os.path.join(files_dir,
                                secrets.token_hex(nbytes=16) + file_ext)
        if 'files' not in os.listdir(os.getcwd()):
            os.makedir(files_dir)
        form.file.data.save(filename)

        return render_template('index.html', title=form.name.data)
    return render_template('upload.html', form=form)
Beispiel #5
0
    def update_post(post_id):

        post = Post.query.get(post_id)
        form = MyForm()
        if form.validate_on_submit():
            post.title = form.title.data
            post.author = form.author.data
            post.content = form.content.data
            post.user_id = current_user.id
            db.session.add(post)
            db.session.commit()
            flash('Post is updated!')
            return redirect(url_for('posts'))
        else:
            return redirect(url_for('posts'))
Beispiel #6
0
def form_view(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MyForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # some actions
            return render(request, 'form_was_valid.html')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = MyForm()

    return render(request, 'form.html', {'form': form})
def AddObserve():
    form = MyForm()
    if form.validate_on_submit():
        sx = pd.Series(
            [
                form.EmploymentField.data, form.EmploymentStatus.data,
                form.Gender.data, form.LanguageAtHome.data,
                form.JobWherePref.data, form.SchoolDegree.data,
                form.Income.data
            ],
            index=
            "EmploymentField, EmploymentStatus, Gender, LanguageAtHome, JobWherePref, SchoolDegree, Income"
            .split(", "))
        fw.append(sx)
        # здесь логика базы данных
        return redirect(url_for('contact'))
    return render_template('AddObserve.html', form=form)
Beispiel #8
0
def input_data():
    form = MyForm(request.form)
    if request.method == 'POST':
        name = form.data.get('name')
        add_record_task.delay(name)
        return redirect('/input/')
    if request.method == 'GET':
        records = get_records_sync_task()
        return render_template('form.html', form=form, records=records)
Beispiel #9
0
def index():
    form = MyForm()
    get_db()
    WTF_CSRF_SECRET_KEY = 'a random string'
    if form.validate_on_submit():
        print("Query")
        user = User.query.filter_by(username=form.log_in_name.data).first()
        if user:
            print("found user")
            if check_password_hash(user.password_hash, form.password.data):
                login_user(user, remember=True)
                flash("success")
                if (user.role == "support"):
                    return redirect(url_for('createticket'))
                if (user.role == "sales"):
                    return redirect(url_for('searchcustomer'))
        return '<h1>Invalid username or password</h1>'
    return render_template('index.html', form=form)
Beispiel #10
0
def index():
    form = MyForm()
    if request.method == 'POST':
        if form.validate():
            username = form.data['name']
            password = form.data['password']
            date = form.data['date']
            reminder = form.data['reminder']

            user = iCalPro()
            result = user.iCalPro(username, password, date.strftime('%Y%m%d'),
                                  reminder)  # Tuple
            session['res'] = result

            return redirect(url_for('subscribe'))  # 失败处理 flash 消息
        else:
            flash('请检查日期正确性,并以"Year/Month/Day"格式正确填写😬')
    return render_template('index.html', form=form)
Beispiel #11
0
def upload():
    form = MyForm()
    if form.validate_on_submit():
        f = form.file.data
        filename = str(uuid.uuid4())[:5]+'.'+f.filename.split('.')[-1]
        print(filename) 
        startTime = datetime.now()
        if(os.path.exists(os.path.join(os.getcwd(), 'app', 'files'))):
            f.save(os.path.join(os.getcwd(), 'app', 'files', filename))
            with open(os.path.join(os.getcwd(), 'app', 'files', filename), 'r') as f_:
                data = counter.count_letters_RU(f_.read())
                print(data)
                counter.make_letters_hist(data, os.path.join(os.getcwd(), 'app', 'files', filename.split('.')[0]))
            
            return render_template('index.html', fname=str(f.filename), data = data, imgname = filename.split('.')[0], takeTime = datetime.now() - startTime)
        else:
            return render_template('upload.html', form=form)
        
    return render_template('upload.html', form=form)
Beispiel #12
0
 def posts():
     form = MyForm()
     data = request.data
     if request.method == 'POST':
         post = Post(title=form.title.data,
                     author=form.author.data,
                     content=form.content.data)
         db.session.add(post)
         db.session.commit()
         return redirect(url_for('posts'))
     else:
         posts = Post.query.all()
         return render_template('post_list.html', posts=posts)
Beispiel #13
0
def register(request):
    form = MyForm()
    if request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
        else:
            return render(request, 'register.html', {'form': form})
    else:
        return render(request, 'register.html', {'form': form})
def profile():
    form = MyForm()
    if request.method=='POST' and form.validate_on_submit():
        firstname=request.form['firstname']
        lastname=request.form['lastname']
        gender=request.form['gender']
        email=request.form['email']
        location=request.form['location']
        biography=request.form['biography']
        profilepic = form.profilepic.data
        
        
        filename=secure_filename(profilepic.filename)
        profilepic.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
        
        userprofile = UserProfile(firstname,lastname,gender,email,location,biography, filename)
        db.session.add(userprofile)
        db.session.commit()
        
        flash('Yup. you been added')
        return redirect(url_for('Users'))
        
    return render_template('profile.html', form=form)
Beispiel #15
0
def add():
    form = MyForm()
    if form.validate_on_submit():
        name = request.form['name']
        ingridients = request.form['ingridients']
        url = request.form['url']
        url_img = request.form['url_img']
        category = request.form['category']
        time = request.form['time']

        recipe = Recipe(name=name,
                        ingridients=ingridients,
                        url=url,
                        url_img=url_img,
                        category=category,
                        time=time)
        print(recipe)

        db.session.add(recipe)
        db.session.commit()
        print('Sucsess!!!')

    return render_template('add.html', active='donate'.lower(), form=form)
def profile():
    myform = MyForm()

    if request.method == 'POST':
        if myform.validate_on_submit():
            fname = myform.fname.data
            lname = myform.lname.data
            gender = myform.gender.data
            email = myform.email.data
            location = myform.location.data
            biography = myform.biography.data
            upload = myform.upload.data

            filename = secure_filename(upload.filename)
            upload.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            filename = secure_filename(upload.filename)

            profile_date = datetime.date.today().strftime("%b %d, %Y")
            user_id = genId(fname, lname, location)

            new_profile = UserProfile(fname=fame,
                                      lame=lname,
                                      gender=gender,
                                      email=email,
                                      location=location,
                                      biography=biography,
                                      upload=filename,
                                      profile_creation=profile_date)

            db.session.add(new_profile)
            db.session.commit()

            flash('Profile added!')
            return redirect(url_for("profiles"))

        flash_errors(myform)
    return render_template('profile.html', form=myform)
Beispiel #17
0
def xtm():
    form = MyForm()
    if form.validate_on_submit():
        tm = False
        states = parser1.dict_parse(form.states.data)
        states_dict = literal_eval(states)
        input_s = parser1.dict_parse(form.input_symbols.data)
        input_symbols_dict = literal_eval(input_s)
        tape_s = parser1.dict_parse(form.tape_symbols.data)
        tape_symbols_dict = literal_eval(tape_s)

        initial_state_d = form.initial_state.data
        if form.left_end.data:
            left_end_d = form.left_end.data
        else:
            left_end_d = '>'
        try:
            transitions_d = literal_eval(form.prechody.data)
        except:
            transitions_d = {}
            success_message = ("Neočakávaná chyba v prechodovej funkcii")
            flash(success_message)

        if form.blank_symbol.data:
            blank_symbol_d = form.blank_symbol.data
        else:
            blank_symbol_d = '#'
        reject_state_d = form.reject_state.data
        final_states_d = form.final_states.data
        try:
            xdtm = XDTM(states=states_dict,
                        input_symbols=input_symbols_dict,
                        tape_symbols=tape_symbols_dict,
                        left_end=left_end_d,
                        transitions=transitions_d,
                        initial_state=initial_state_d,
                        blank_symbol=blank_symbol_d,
                        reject_state=reject_state_d,
                        final_states=final_states_d)
            if xdtm:
                tm = True
        except (exceptions.InvalidStateError, exceptions.InvalidSymbolError,
                exceptions.MissingStateError, exceptions.MissingSymbolError,
                exceptions.InitialStateError, exceptions.FinalStateError,
                exceptions.RejectStateError, exceptions.LeftEndError,
                exceptions.RejectionError, exceptions.InvalidDirectionError,
                exceptions.Badcounttapes) as err:
            tm = False
            success_message = (err)
            flash(success_message)
        if tm:
            try:
                tmachine = Tmachine(definicia=form.funkcia.data,
                                    tm_d_n_x='xtm')
                db.session.add(tmachine)
                db.session.commit()
            except exc.IntegrityError:
                db.session().rollback()
                tm = False
                success_message = (
                    "Definícia/Názov TM už existuje prosím zvolte iný názov")
                flash(success_message)
        if tm:
            name = str(tmachine.id)
            with open("tm{}.py".format(name), "w") as text_file:
                text_file.write(
                    "from turing_machine.xdtm import XDTM \nxdtm = XDTM("
                    "\nstates = {0}"
                    ",\ninput_symbols = {1},"
                    "\ntape_symbols = {2},\nleft_end = '{3}',"
                    "\ntransitions = {4},"
                    "\ninitial_state = '{5}',\nblank_symbol = '{6}',"
                    "\nreject_state = '{7}', \nfinal_states = '{8}' \n)".
                    format(states_dict, input_symbols_dict, tape_symbols_dict,
                           left_end_d, transitions_d, initial_state_d,
                           blank_symbol_d, reject_state_d, final_states_d))
            success_message = ('Nový viac páskový DTM: ' + form.funkcia.data +
                               ' je vytvorený')
            flash(success_message)
            return redirect(url_for('index'))
    return render_template('xtm.html', title='XTM', form=form)
Beispiel #18
0
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/success')
    return render_template('submit.html', form=form)
Beispiel #19
0
def form_test():
    form = MyForm()
    if request.method == "POST" and form.validate_on_submit():
        return redirect(url_for("form_output", text="test1"))
    return render_template("form.html", form=form)
Beispiel #20
0
 def new_post():
     form = MyForm()
     return render_template('post_form.html', form=form, url="/posts")
Beispiel #21
0
 def edit_post(post_id):
     post = Post.query.get(post_id)
     form = MyForm(obj=post)
     return render_template('post_form.html', form=form, url="/post/" + post_id + "/update")
Beispiel #22
0
def form():
    form = MyForm()
    if form.validate_on_submit():
        return render_template('result.html', email=form.email.data, password=form.password.data, textarea=form.textarea.data, radios=form.radios.data, selects=form.selects.data)
    return render_template('form.html', form=form)