Ejemplo n.º 1
0
def register():
    # """Register user"""
    # https://flask.palletsprojects.com/en/1.1.x/patterns/wtforms/

    # Both of these lines work - I am using the fist form
    form = RegisterForm()
    #form = RegisterForm(request.form)

    # Either if request.method == "POST" OR form.validate_on_submit(): works
    # The form.validate_on_submit() method does all the form processing work.
    # https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms

    # if request.method == "POST":

    if form.validate_on_submit():
        user = People(username=form.username.data,
                      email=form.email.data,
                      first_name=form.first_name.data,
                      last_name=form.last_name.data,
                      comments=form.password.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        #flash('Register requested for user {}, firstName={}, lastName={}'.format(
        #    form.username.data, form.firstName.data, form.lastName.data))
        flash(
            'Congratulations, you are now a registered user!<br>Please Log In.',
            "success")
        return redirect(url_for('auth.login'))

    form.submit.label.text = 'Register'
    return render_template('auth/register.html', title='Register', form=form)
Ejemplo n.º 2
0
def applyjob(request, job_id):
    if request.session.has_key('profile'):
        return redirect("/")
    timestamp = time.time()
    locals().update(csrf(request))
    job = Job.objects.get(pk=job_id)
    job_one_type = ((x.pk, x)
                    for x in Job.objects.filter(degree_limit=job.degree_limit))
    if request.method == 'POST':
        peopleForm = PeopleForm(request.POST)
        if peopleForm.is_valid():
            data = peopleForm.cleaned_data
            data['audit_step'] = 0
            data['query_password'] = hashlib.md5(
                data['query_password']).hexdigest()
            del data['query_password2']

            # 复制图片到相应目录
            avatar_path = "/".join(
                ('static/upload/', peopleForm.cleaned_data["id_number"]))
            if not os.path.exists(avatar_path):
                os.mkdir(avatar_path)
            src_file = peopleForm.cleaned_data["avatar"][1:]
            dst_file = "/".join(
                (avatar_path,
                 os.path.basename(peopleForm.cleaned_data["avatar"])))
            if src_file != dst_file:
                try:
                    shutil.move(src_file, dst_file)
                    peopleForm.cleaned_data["avatar"] = '/%s' % (dst_file, )
                except Exception:
                    pass

            people = People(**data)
            people.save()
            request.session['profile'] = people
            request.session.set_expiry(3600)
            message = u'信息提交成功<a href="/myinfo/">查看</a>已提交的信息'
            return render_to_response("msg.html", locals())
        else:
            peopleForm.fields['job'] = forms.ChoiceField(
                widget=forms.Select(),
                choices=tuple([('', '---------')] + list(job_one_type)),
                initial=job)
    else:
        peopleForm = PeopleForm(initial={'job': job_id})
        peopleForm.fields['job'] = forms.ChoiceField(
            widget=forms.Select(),
            choices=tuple([('', '---------')] + list(job_one_type)),
            initial=job)
    response = render_to_response("apply.html", locals())
    response['Pragma'] = 'no-cache'
    response['Cache-Control'] = 'no-cache must-revalidate proxy-revalidate'
    return response
Ejemplo n.º 3
0
def applyjob(request, job_id):
    if request.session.has_key('profile'):
        return redirect("/")
    timestamp = time.time()
    locals().update(csrf(request))
    job = Job.objects.get(pk=job_id)
    job_one_type = ((x.pk, x) for x in Job.objects.filter(degree_limit=job.degree_limit))
    if request.method == 'POST':
        peopleForm = PeopleForm(request.POST)
        if peopleForm.is_valid():
            data = peopleForm.cleaned_data
            data['audit_step'] = 0
            data['query_password'] = hashlib.md5(data['query_password']).hexdigest()
            del data['query_password2']
            
            # 复制图片到相应目录
            avatar_path = "/".join(('static/upload/', peopleForm.cleaned_data["id_number"]))
            if not os.path.exists(avatar_path):
                os.mkdir(avatar_path)
            src_file = peopleForm.cleaned_data["avatar"][1:]
            dst_file = "/".join((avatar_path, os.path.basename(peopleForm.cleaned_data["avatar"])))
            if src_file!=dst_file:
                try:
                    shutil.move(src_file, dst_file)
                    peopleForm.cleaned_data["avatar"] = '/%s' % (dst_file, )
                except Exception:
                    pass
            
            people = People(**data)
            people.save()
            request.session['profile'] = people
            request.session.set_expiry(3600)
            message = u'信息提交成功<a href="/myinfo/">查看</a>已提交的信息'
            return render_to_response("msg.html", locals())
        else:
            peopleForm.fields['job'] = forms.ChoiceField(
                widget=forms.Select(), 
                choices=tuple([('', '---------')] + list(job_one_type)), 
                initial=job)
    else:
        peopleForm = PeopleForm(initial={'job': job_id})
        peopleForm.fields['job'] = forms.ChoiceField(
            widget=forms.Select(), 
            choices=tuple([('', '---------')] + list(job_one_type)), 
            initial=job)
    response = render_to_response("apply.html", locals())
    response['Pragma'] = 'no-cache'
    response['Cache-Control'] = 'no-cache must-revalidate proxy-revalidate'
    return response
Ejemplo n.º 4
0
def input_people(request):
    result = []
    with open('D:\python\工资管理系统\SalaryManageSystem\database_people.csv',
              'r',
              encoding='UTF-8') as f:
        reader = csv.reader(f)
        for items in reader:
            if reader.line_num == 1:
                continue
            test = People(id=int(items[0]),
                          name=items[1],
                          sex=items[2],
                          year=int(items[3]),
                          job=items[4],
                          department=items[5])
            test.save()
    return HttpResponse('ok')
Ejemplo n.º 5
0
def testdb(request):
    test1 = People(id=101,
                   name='吴进军',
                   sex='男',
                   year=6,
                   job='老板',
                   department='督导层')
    test2 = salary(id=101,
                   name='lqy',
                   salary=100,
                   Bonus=0,
                   fakuan=50,
                   Overtime_pay=200)
    test3 = user(user='******', password='******')
    test1.save()
    test2.save()
    test3.save()
    return HttpResponse("<p>数据添加成功!</p>")
Ejemplo n.º 6
0
def contact():
    form = Contact()
    if form.validate_on_submit():
        contact = People(name=form.name.data,email=form.email.data,msg=form.message.data)
        db.session.add(contact)
        db.session.commit()
        send_mail('Someone contacted you!',app.config['ADMINS'][0],app.config['MY_MAIL'][0],render_template('email/contact_message_sent.txt',user=contact),render_template('email/contact_message_sent.html',user=contact))
        flash('Thank you for reaching out!','success')
        return redirect(url_for('index'))

    return render_template('contact.html', title='Simon Gschnell', form=form)
Ejemplo n.º 7
0
def import_excels():
    form_data = []
    exceldir = "/Users/lishun/PycharmProjects/solution_project/app/static/video/people.xlsx"
    bk = open_workbook(exceldir, encoding_override="utf-8")
    try:
        sh = bk.sheets()[0]
    except:
        print("no sheet in %s named sheet1" % exceldir)
    else:
        nrows = sh.nrows
        for i in range(1, nrows):
            row_data = sh.row_values(i)
            people = People()
            people.id = row_data[0]
            people.name = row_data[1]
            people.age = row_data[2]
            form_data.append(row_data)
            #     db.session.add(people)
            # db.session.commit()
    return render_template('admin/import_device.html', form_data=form_data)
Ejemplo n.º 8
0
def inset_people(request):
    global userid
    if request.POST:
        post = request.POST
        id = post["id"]
        new_salary = Salary(salaryid_id=id, hour=0, plus=0, forfeit=0, sub=0)
        new_people = People(peopleid=id,
                            name=post["name"],
                            nation=post["nation"],
                            phone=post["phone"],
                            email=post["email"],
                            date=post["date"],
                            address=post["address"],
                            birthday=post["birthday"],
                            ptype_id=Salary_type.objects.get(
                                typename=post["post_name"]).salary_typeid,
                            allsalary=Salary_type.objects.get(
                                typename=post["post_name"]).base_pay)
        if post["sex"] == "M":
            new_people.sex = True
        else:
            new_people.sex = False
        new_people.save()
        new_salary.save()
    return render_to_response("insert_people.html")
Ejemplo n.º 9
0
def create_people(db: SQLAlchemy, data: List[PeopleData]):
    for item in data:
        people = People.query.filter_by(imdb_id=item.imdb_id).first()

        if people is None:
            item.look_up()
            people = People(imdb_id=item.imdb_id,
                            imdb_url=item.imdb_url,
                            full_name=item.full_name,
                            bio=item.bio,
                            avatar=item.avatar,
                            born_info=item.born_info,
                            death_info=item.death_info)
        else:
            people.imdb_url = item.imdb_url
            people.full_name = item.full_name

        for job in create_job_categories(db, item.job_categories):
            people.job_categories.append(job)

        db.session.add(people)

        yield people
Ejemplo n.º 10
0
def add_people(request):
    people = People()
    people.name = '后羿%d' % random.randrange(100)
    people.sex = '男'
    people.save()
    card = Card()
    card.num = random.randrange(100000, 200000)
    card.cid = people
    card.save()
    return HttpResponse('添加成功')
Ejemplo n.º 11
0
def addPeople():
    form = ProductForm()
    if request.method == 'POST':
        data = form.data
        file_img = secure_filename(form.img.data.filename)
        if not os.path.exists(app.config["UP_DIR"]):
            os.makedirs(app.config["UP_DIR"])
            os.chmod(app.config["UP_DIR"], "rw")
        img = change_filename(file_img)
        form.img.data.save(app.config["UP_DIR"] + img)
        product = People(name=data["name"], img=img, content=data["content"])
        db.session.add(product)
        db.session.commit()
        flash("添加成功!")
        return redirect(url_for("admin.people", page=1))
    return render_template("admin/peopleAdd.html", form=form)
Ejemplo n.º 12
0
def create_people(current_user, first_name, last_name, phone_cell, ptype,
                  pstatus, notes, house_number, street_name, city_name,
                  state_name, zip_code):
    currentuser = User.query.filter_by(username=current_user.username).first()
    user_account_pk = currentuser.id
    new_people = People(first_name=first_name,
                        last_name=last_name,
                        phone_cell=phone_cell,
                        ptype=ptype,
                        pstatus=pstatus,
                        notes=notes,
                        house_number=house_number,
                        street_name=street_name,
                        city_name=city_name,
                        state_name=state_name,
                        zip_code=zip_code,
                        user_account_pk=user_account_pk)
    db.session.add(new_people)
    db.session.commit()
    return True
Ejemplo n.º 13
0
def reset_password(token):

    if current_user:
        if current_user.is_authenticated:
            return redirect(url_for('main.index'))

    person = People.verify_reset_password_token(token)
    if not person:
        return redirect(url_for('main.index'))

    form = ResetPasswordForm()
    if form.validate_on_submit():
        person.comments = form.password.data
        person.set_password(form.password.data)
        db.session.commit()
        flash('Your password has been reset.', "success")
        return redirect(url_for('auth.login'))

    return render_template('email/reset_password.html',
                           title='Reset Password',
                           form=form)
Ejemplo n.º 14
0
def people_edit(cl_people_id):
    if current_user.is_authenticated == False:
        flash(f'Must be logged in to curate people')
        return redirect(url_for('index'))
    people = People()
    people.load(cl_people_id)
    form = PeopleForm()
    if form.validate_on_submit():
        people.cl_people_id = form.cl_people_id.data
        people.family_name = form.family_name.data
        people.given_name = form.given_name.data
        people.thesis_id = form.thesis_id.data
        people.authors_id = form.authors_id.data
        people.archivesspace_id = form.archivesspace_id.data
        people.directory_id = form.directory_id.data
        people.viaf = form.viaf.data
        people.lcnaf = form.lcnaf.data
        people.isni = form.isni.data
        people.wikidata = form.wikidata.data
        people.snac = form.snac.data
        people.orcid = form.orcid.data
        people.image = form.image.data
        people.educated_at = form.educated_at.data
        people.caltech = form.caltech.data
        people.jpl = form.jpl.data
        people.faculty = form.faculty.data
        people.alumn = form.alumn.data
        people.notes = form.notes.data
        c_name = cfg.OBJECTS
        key = people.cl_people_id
        now = datetime.now()
        if dataset.key_exists(c_name, key):
            err = dataset.update(c_name, key, people.to_dict())
            if err != '':
                flash(f'WARNING: failed to update {key} in {c_name}, {err}')
            else:
                flash(f'{people.cl_people_id} updated {now}')
        else:
            err = dataset.create(c_name, key, people.to_dict())
            if err != '':
                flash(f'WARNING: failed to create {key} in {c_name}, {err}')
            else:
                flash(f'{people.cl_people_id} created {now}')
    else:
        form.cl_people_id.data = people.cl_people_id
        form.family_name.data = people.family_name
        form.given_name.data = people.given_name
        form.thesis_id.data = people.thesis_id
        form.authors_id.data = people.authors_id
        form.archivesspace_id.data = people.archivesspace_id
        form.directory_id.data = people.directory_id
        form.viaf.data = people.viaf
        form.lcnaf.data = people.lcnaf
        form.isni.data = people.isni
        form.wikidata.data = people.wikidata
        form.snac.data = people.snac
        form.orcid.data = people.orcid
        form.image.data = people.image
        form.educated_at.data = people.educated_at
        form.caltech.data = people.caltech
        form.jpl.data = people.jpl
        form.faculty.data = people.faculty
        form.alumn.data = people.alumn
        form.notes.data = people.notes
    return render_template('people_edit.html',
                           title="Edit Person",
                           user=current_user,
                           form=form)
Ejemplo n.º 15
0
def get_number():
    """排号 涉及办事人员表添加取号记录,办事表查询和添加记录,队列"""
    # 获取数据
    req_dict = request.get_json()
    subject = req_dict.get('subject', "")  # 主题
    item = req_dict.get('item', "")  # 事项
    mobile = req_dict.get('mobile', "")  # 电话
    idno = req_dict.get('idno', "")  # 身份证
    addr = req_dict.get('work_addr', "")  # 地址
    print("++++取号++++", req_dict)
    # 校验数据
    param_keys = ["subject", "item", "mobile", "idno", "work_addr"]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    # 判断手机号格式
    if not re.match(r"1[34578]\d{9}", mobile):
        # 表示格式不对
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")
    # 判断身份证号
    if not re.match(r"[1-9]\d{16}[0-9a-zA-Z]", idno):
        return jsonify(errno=RET.PARAMERR, errmsg="身份证格式错误")
    # 记录对应主题取号总量
    redis_store.incr(addr + subject + "total_number")
    totle = int(
        redis_store.get(addr + subject + "total_number").decode("utf-8"))
    print("取号总量-----------", totle)
    # 查询办事表检查当事人是否来过
    try:
        current_people = People.query.filter_by(idno=idno).first()
        current_addr = Addr.query.filter_by(name=addr).first()
        current_subject = Subject.query.filter_by(name=subject).first()
        current_item = Item.query.filter_by(name=item).first()
        current_location = Location.query.filter_by(subject=subject).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 生成流水号
    water_num = current_addr.seq + datetime.now().strftime(
        "%Y%m%d%H%M%S") + str(current_item.id).rjust(3, '0')
    # 生成号码
    number = current_subject.seq + str((0 + totle * 1) % 1000).rjust(3, '0')
    # 记录事件
    current_business = Business(water_num=water_num,
                                idno=idno,
                                addr=addr,
                                subject=subject,
                                item=item,
                                process=current_item.process,
                                current_process="接件",
                                in_deal=0,
                                is_scene=0,
                                number=number,
                                timeout=current_item.timeout,
                                takan_used_time=0,
                                wait_seconds=0,
                                move_times=0)
    age = datetime.now().year - int(idno[6:10])
    sex = int(idno[16:17]) % 2
    try:
        db.session.add(current_business)
        if not current_people:
            current_people = People(idno=idno, mobile=mobile)
            db.session.add(current_people)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 添加队列
    try:
        # 发送短信
        length = redis_store.llen(addr + subject)
        location = current_location.location
        try:
            result = current_app.config['MSG_SENDER'].send_with_param(
                86,
                mobile,
                current_app.config['TEMPLATE_NUMBER'], [
                    number, length, location,
                    datetime.now().strftime('%H:%M:%S')
                ],
                sign=current_app.config['SMS_SIGN'],
                extend="",
                ext="")  # 签名参数未提供或者为空时,会使用默认签名发送短信
            pass
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
        # 添加排队队列
        redis_store.rpush(addr + subject, water_num)
        # 添加排队时间队列
        redis_store.rpush(addr + subject + "time",
                          datetime.now().strftime("%H%M%S"))
        # 添加用户头顶屏幕显示人数
        redis_store.rpush(
            'usershead',
            json.dumps({
                "subject": subject,
                "length": length,
                "show": "true"
            }))
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.SERVERERR, errmsg="内部错误")
    else:
        # 返回流水号,号码,位置,等待人数
        return jsonify(errno=RET.OK,
                       errmsg="成功",
                       data={
                           "water_num": water_num,
                           "number": number,
                           "location": location,
                           "wait": length
                       })