예제 #1
0
def getUserInfo(user):
    """Returns UserInfo associated with User
    Creates one, if it doesn't already exist."""
    try:
        return UserInfo.objects.get(user=user)
    except ObjectDoesNotExist:
        userInfo = UserInfo(user=user)
        userInfo.save()
        return userInfo
예제 #2
0
 def fetch_user_info(self, username):
     endpoint = 'https://api.github.com/users/{0}'.format(username)
     res = self._make_reqeust('GET', endpoint)
     try:
         user_dict = res.json()
     except json.JSONDecodeError:
         user_dict = {}
     else:
         UserInfo.create_one(user_dict)
     return user_dict
예제 #3
0
파일: views.py 프로젝트: Sanagiig/myBlog
def register():
    if request.method == 'POST':
        data = request.get_data().decode('utf-8')
        data = json.loads(data)
        opt = data['opt']
        email = data['email']
        password = data['password']
        check_code = data['check_code']
        result = False

        if opt == 'register':
            if not check_email(email):
                result = 5
            elif not check_password(password):
                result = 4
            elif check_code != session['check_code']:
                result = 3
            elif UserInfo.query.filter_by(email=email).first():
                result = 2
            else:
                u = UserInfo(email=email,
                             password=password,
                             profile_img=gravatar_generator(email),
                             nick_name='第%d个用户' % (UserInfo.query.count() + 1))
                db.session.add(u)
                try:
                    db.session.commit()
                except Exception:
                    session['info'] = '由于服务器数据库原因,注册失败 !'
                else:  #注册成功
                    result = 1

        return jsonify({'result': result})
예제 #4
0
 def _insert_test_user_info(self, session, user_info: dict = {}):
     data = {"user_id": "Test user ID", "name": "Test name"}  # A
     data.update(user_info)
     db_user_info = UserInfo(**data)
     session.add(db_user_info)
     session.commit()
     return db_user_info
예제 #5
0
def home_add(username,email,address):
    from app import db
    from app.models import UserInfo
    admin = UserInfo(username, email, address)
    db.session.add(admin)
    db.session.commit()
    return render_template('index.html')
예제 #6
0
def contact():

    form = FormName()
    if form.validate_on_submit():
        name = form.name.data
        lastname = form.lastname.data
        email = form.email.data
        item = UserInfo(name, lastname, email)
        if UserInfo.read(email):
            pass
        else:
            item.add()

        flash(f"Thank you {name} {lastname} you have successfully sent us a message, we will reach you back on {email}")

        return redirect(url_for("contact.contact"))

    return render_template("contact_us.html", form=form)
예제 #7
0
def home_add_user(username, email, address):
    # 传入Model层, 存储数据库
    from app import db
    from app.models import UserInfo
    user = UserInfo(username=username, email=email, address=address)
    db.session.add(user)
    db.session.commit()
    print('save ok.')
    import json
    data = {'username': username, 'email': email, 'address': address}
    result = {'code': 200, 'message': 'ok', 'data': data}
    return Response(json.dumps(result))
예제 #8
0
    def post(self, user_id=None):
        body = request.get_json()
        connect(app.config['MONGO_URI'])
        #if email id present in mongodb then don't create new user
        new_user = client.create_user(body, "127.0.0.1")
        result = new_user.__dict__

        response = result['body']

        user = UserInfo(user_id=response['_id'],
                        user_refresh_token=response['refresh_token'],
                        logins=response['logins'],
                        phone_numbers=response['phone_numbers'])
        mercury = Mercury(users=[user]).save()
        return response, 201
예제 #9
0
def register(request):
    user = request.user
    if user.is_authenticated:
        logout(request)
        return redirect(to='infomanage')
    if request.method == 'POST':
        form = UserInfoForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            user_exist = User.objects.filter(username=username)
            if user_exist:
                messages.add_message(request, messages.ERROR, "用户名已存在,请更换!")
                return redirect(to='register')
            else:
                password = form.cleaned_data['password']
                User.objects.create_user(username=username, password=password)
                try:
                    acc = User.objects.get(username=username)
                    user = UserInfo()
                    user.account = acc
                    user.sex = form.cleaned_data['sex']
                    user.name = form.cleaned_data['username']
                    user.job = form.cleaned_data['job']

                    num = UserInfo.objects.order_by(
                        'job_num').reverse().all()[0].job_num
                    user.job_num = num + 1

                    user.save()
                    str = "注冊成功!"
                    messages.add_message(request, messages.ERROR, str)

                except:
                    print('error')
                    pass
                return redirect(to='login')

    elif request.method == 'GET':
        form = UserInfoForm
        return render(request, 'register.html', {'form': form})
예제 #10
0
def register(request):
    if request.method == 'POST':
        form = UserInfoForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            user_exist = User.objects.filter(username=username)
            if user_exist:
                messages.add_message(request, messages.ERROR, "用户名已存在,请更换!")
                return redirect(to='register')
            else:
                user = UserInfo()
                user.username = form.cleaned_data['username']
                user.password = form.cleaned_data['password']
                user.sex = form.cleaned_data['sex']
                user.job = form.cleaned_data['job']
                user.job_num = form.cleaned_data['job_num']
                user.save()
                login(request, user)
                return redirect(to='infomanage')

    elif request.method == 'GET':
        form = UserInfoForm
        return render(request, 'register.html', {'form': form})
예제 #11
0
def register():
    form = ClientForm()
    if form.validate_on_submit():
        # hash the password of the form
        hashed = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        # create a new user/client instance with the form fields and commit to our database
        user = UserInfo(first_name=form.first_name.data,
                        last_name=form.last_name.data,
                        email=form.email.data,
                        password=hashed)
        db.session.add(user)
        db.session.commit()
        flash(
            f'User {form.first_name.data} {form.last_name.data}has been created!You can now login in'
        )
        return redirect(url_for('login'))
    else:
        flash('Failed')
    return render_template('register.html', form=form)
예제 #12
0
def userinfo_generator(count=100):
    from app.models import UserInfo
    seed()
    for i in range(count):
        email=forgery_py.internet.email_address()
        u = UserInfo(email='fk' +str(i) + email,
                     nick_name = forgery_py.internet.user_name()+str(i),
                     password='******',
                     name=forgery_py.name.full_name(),
                     motto=forgery_py.lorem_ipsum.sentence()[:-110],
                     member_since=forgery_py.date.date(True),
                     last_seen=forgery_py.date.date(True),
                     profile_img=gravatar_generator(email))
        db.session.add(u)
        try:
            db.session.commit()
        except Exception as e :
            print('生成用户信息时出错 !')
            print(e)
            db.session.rollback()
예제 #13
0
def signup(request):
    if request.method == 'GET':
        form = CustomizedUserCreationForm()
        context = {"form": form}
        return render(request, 'signup.html', context=context)
    else:
        form = CustomizedUserCreationForm(request.POST)
        context = {"form": form}
        if form.is_valid():
            user = form.save()
            if user is not None:
                ui = UserInfo()
                ui.user = user
                ui.status = 'OFFLINE'
                ui.save()
                return redirect('login')
        else:
            return render(request, 'signup.html', context=context)
예제 #14
0
파일: views.py 프로젝트: sw-iknow/toknow2
def registration(request):
    logger.debug("REGISTRATION")
    if request.user.is_active:
        return HttpResponse("Already registered")
    else:
        username = request.POST.get('username', '')
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        skill1 = request.POST.get('skill1', '')
        skill2 = request.POST.get('skill2', '')
        skill3 = request.POST.get('skill3', '')
        skill1info = request.POST.get('skill1info', '')
        skill2info = request.POST.get('skill2info', '')
        skill3info = request.POST.get('skill3info', '')
        logger.debug("reg user:"******"reg pw:" + password)
        if email:
            try:
                u = User.objects.create_user(username=str(username), email=email, password=str(password))
                u.set_password(password)
                u.save()
            except Exception:
                return HttpResponse("This username is taken.")
            user = auth.authenticate(username=str(username), password=str(password))
            ui = UserInfo(message="{}::{}::{}".format(skill1, skill2, skill3), authuser_id_id=u.id)
            ui.save()

            if skill1:
                try:
                    s = SkillType.objects.get(name=skill1)
                except Exception:
                    s = SkillType(level=1,name=skill1)
                    s.save()
                if s:
                    si = SkillInstance(user_id=ui, skill_type_id=s, instance_type="Offer",snippet=skill1info)
                    si.save()

            if skill2:
                try:
                    s = SkillType.objects.get(name=skill2)
                except Exception:
                    s = SkillType(level=1,name=skill2)
                    s.save()
                if s:
                    si = SkillInstance(user_id=ui, skill_type_id=s, instance_type="Offer",snippet=skill2info)
                    si.save()

            if skill3:
                try:
                   s = SkillType.objects.get(name=skill3)
                except Exception:
                    s = SkillType(level=1,name=skill3)
                    s.save()
                if s:
                    si = SkillInstance(user_id=ui, skill_type_id=s, instance_type="Offer",snippet=skill3info)
                    si.save()

            
            auth.login(request, user)
            return redirect("/")

        template = loader.get_template('app/registration.html')
        context = RequestContext(request, {
            'current_user': str(request.user),
            "page": "registration",
        })
        logger.debug("Data: " + str(email) + " " + str(password) + " " + str(skill1))

        return HttpResponse(template.render(context))
예제 #15
0
def Daily(username):
    user = User.query.filter_by(username=username).first_or_404()
    form = DailyForm()
    if request.method == "POST":
        berry = int(form.berry.data)
        avocado = int(form.avocado.data)
        tomato = int(form.tomato.data)
        banana = int(form.banana.data)
        apple = int(form.apple.data)
        citrus = int(form.citrus.data)
        beef = int(form.beef.data)
        lamb = int(form.lamb.data)
        prawn = int(form.prawn.data)
        fish = int(form.fish.data)
        pork = int(form.pork.data)
        chicken = int(form.chicken.data)
        cheese = int(form.cheese.data)
        egg = int(form.egg.data)
        tofu = int(form.tofu.data)
        bean = int(form.bean.data)
        pea = int(form.pea.data)
        nut = int(form.nut.data)
        rice = int(form.rice.data)
        pasta = int(form.pasta.data)
        oat = int(form.oat.data)
        bread = int(form.bread.data)
        potato = int(form.potato.data)
        milk = int(form.milk.data)
        pl_milk = int(form.pl_milk.data)
        beer = int(form.beer.data)
        coffee = int(form.coffee.data)
        wine = int(form.wine.data)
        tea = int(form.tea.data)
        ecar = int(form.ecar.data)
        gcar = int(form.gcar.data)
        train = int(form.train.data)
        bus = int(form.bus.data)
        plane = int(form.plane.data)
        gas = int(form.gas.data)
        electricity = int(form.electricity.data)
        fuel = int(form.fuel.data)
        propane = int(form.propane.data)
        week = int(form.week.data)

        ##calc home energy ##
        enCoeff = {"gas": 2.8, "elec": 1.29, "fuel": 1.41, "propane": 1.26}
        enTotal = enCoeff["gas"] * gas + enCoeff[
            "elec"] * electricity + enCoeff["fuel"] * fuel + enCoeff[
                "propane"] * propane

        ##calc Transport ##
        transCo = {"gcar": 1.05, "ecar": 0.66, "train": (1 / 3), "plane": 0.5}
        transTotal = int(transCo["gcar"] * gcar + transCo["ecar"] * ecar +
                         transCo["train"] * train + transCo["plane"] * plane)

        #food calc##
        foodList = [
            berry, avocado, tomato, banana, apple, citrus, beef, lamb, prawn,
            fish, pork, chicken, cheese, egg, tofu, bean, pea, nut, rice,
            pasta, oat, bread, potato, milk, pl_milk, beer, coffee, wine, tea
        ]
        foodName = [
            "berry", "avocado", "tomato", "banana", "apple", "citrus", "beef",
            "lamb", "prawn", "fish", "pork", "chicken", "cheese", "egg",
            "tofu", "bean", "pea", "nut", "rice", "pasta", "oat", "bread",
            "potato", "milk", "pl_milk", "beer", "coffee", "wine", "tea"
        ]
        foodDict = {
            "berry": 0.24,
            "avocado": 0.39,
            "tomato": 0.33,
            "banana": 0.13,
            "apple": 0.07,
            "citrus": 0.065,
            "beef": 15.43,
            "lamb": 8.47,
            "prawn": 6.68,
            "fish": 3.84,
            "pork": 3.67,
            "chicken": 3.18,
            "cheese": 2.27,
            "egg": 1.58,
            "tofu": 0.47,
            "bean": 0.22,
            "pea": 0.07,
            "nut": 0.04,
            "rice": 0.73,
            "pasta": 0.26,
            "oat": 0.20,
            "bread": 0.14,
            "potato": 0.12,
            "milk": 1.35,
            "pl_milk": 0.41,
            "beer": 1.41,
            "coffee": 0.92,
            "wine": 0.68,
            "tea": 0.87
        }
        foodOut = 0
        for i in range(len(foodList)):
            foodOut += foodDict[foodName[i]] * foodList[i]

        foodOut = int(foodOut) // 2
        out = foodOut + transTotal + enTotal
        #bf1=bf1, bf2=bf2, bf3=bf3,lf1=lf1,lf2=lf2,df1=df1, df2=df2, df3=df3, transport=tn1,distance=ta1, enSource=et1, enAmt=ea1,
        info = UserInfo(berry=berry,
                        avocado=avocado,
                        tomato=tomato,
                        banana=banana,
                        apple=apple,
                        citrus=citrus,
                        beef=beef,
                        lamb=lamb,
                        prawn=prawn,
                        fish=fish,
                        pork=pork,
                        chicken=chicken,
                        cheese=cheese,
                        egg=egg,
                        tofu=tofu,
                        bean=bean,
                        pea=pea,
                        nut=nut,
                        rice=rice,
                        pasta=pasta,
                        oat=oat,
                        bread=bread,
                        potato=potato,
                        milk=milk,
                        pl_milk=pl_milk,
                        beer=beer,
                        coffee=coffee,
                        wine=wine,
                        tea=tea,
                        ecar=ecar,
                        gcar=gcar,
                        train=train,
                        bus=bus,
                        plane=plane,
                        gas=gas,
                        electricity=electricity,
                        fuel=fuel,
                        propane=propane,
                        user=current_user.username,
                        totalOut=out,
                        foodOut=foodOut,
                        enOut=enTotal,
                        week=week,
                        transOut=transTotal,
                        author=current_user)
        db.session.add(info)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('dailyform.html',
                           title='Fill In Your Daily Info',
                           form=form)
예제 #16
0
	def register_user(userinfo):
		user = UserInfo()
		user.user_id = str(uuid.uuid1())
		if userinfo.password :
			user.password = generate_password_hash(userinfo.password.data)
		else :
			user.password = generate_password_hash(DevelopmentConfig.DEFAULT_PASSWORD)
		user.reg_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
		user.email = userinfo.email.data
		user.user_name = userinfo.username.data
		user.nick_name = userinfo.nickname.data
		user.college_name = userinfo.college.data
		user.major_name = userinfo.major.data
		user.grade = userinfo.grade.data
		user.classnum = userinfo.classnum.data
		user.level = '1'
		dbs.session.add(user)
		dbs.session.commit()
예제 #17
0
def get_facebook_info(user):
    access_token = SocialToken.objects.filter(
        account__user=user, account__provider='facebook').first()

    graph = facebook.GraphAPI(access_token=access_token, version=2.10)
    fb_info = [
        'name', 'location', 'hometown', 'friends', 'education', 'birthday',
        'religion', 'age_range'
    ]

    fb_user_info = graph.get_object(id='me', fields=', '.join(fb_info))

    user_info = UserInfo()
    for k in fb_user_info:
        if k in fb_info:
            if k == 'education':
                temp = fb_user_info['education']
                user_info.education = temp[-1]['school']['name']
            if k == 'location':
                user_info.location = fb_user_info['location']['name']
            if k == 'hometown':
                user_info.hometown = fb_user_info['hometown']['name']
            if k == 'friends':
                user_info.num_friends = fb_user_info['friends']['summary'][
                    'total_count']
            if k == 'name':
                user_info.name = fb_user_info['name']
            if k == 'age_range':
                user_info.age_range = fb_user_info['age_range']['min']
            if k == 'religion':
                user_info.religion = fb_user_info['religion']
    user_info.save()