Ejemplo n.º 1
0
def update_category():
    """
    Updates a category.
    """

    category_id = request.form['id']
    c = CategoryModel.query.get(category_id)
 
    if c.name == "Uncategorised":
        return render_template(
        'admin.html',
        categories=category_controller.list(),
        status=False,
        action='updated',
        operation='categories',
        message="You can't change the name of this category"
        )

    c.name = request.form['title']
   
    db_session.add(c)
    db_session.commit()
    status = True

    return render_template(
        'admin.html',
        categories=category_controller.list(),
        status=status,
        action='updated',
        operation='categories'
    )
Ejemplo n.º 2
0
def club_pictures(rowkey):
    if not check_auth(request):
        abort(403)
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return make_response('No file part', 400)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            return make_response('No file part', 400)
        if not allowed_file(file.filename):
            return make_response('The filetype is not allowed')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filename = rowkey + "." + filename.rsplit('.', 1)[1]
            file.save(os.path.join(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], filename))
            db_picture = db_session.query(UserFile).filter_by(owner=rowkey, file_type='ProfilePicture')
            if len(list(db_picture)) == 0:
                db_picture = UserFile()
                db_picture.file_type = 'ProfilePicture'
                db_picture.owner = rowkey
                db_session.add(db_picture)
                db_session.commit()
                return make_response("",200)
            db_picture.update({"file_name":filename})
            db_session.commit()
            return make_response("", 200)
    if request.method == 'GET':
        filename = db_session.query(UserFile).filter_by(file_type='ProfilePicture', owner=rowkey)[0].file_name
        return jsonify({"filename":  str.replace(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], "static\\Sloach\\", "") + "/" + filename})
Ejemplo n.º 3
0
def statistics_payment_fill():
    cars_count = 100
    year_b = 2000
    month_b = 10
    day_b = 1

    year_e = 2014
    month_e = 11
    day_e = 1
    for x in range(0, cars_count):
        start_time = time.mktime(datetime.date(year_b, month_b, day_b).timetuple())
        end_time = time.mktime(datetime.date(year_e, month_e, day_e).timetuple())

        date = random.randrange(int(start_time), int(end_time))
        activation_time = datetime.datetime.fromtimestamp(date)

        car_number = (random.choice(string.ascii_letters) + random.choice(string.ascii_letters) + " "+ str(random.randint(1000,9999))+ random.choice(string.ascii_letters) + random.choice(string.ascii_letters)).upper()
        cost = random.randint(10,90)
        place_id = random.randint(1,6)
        transaction = 'string'

        pricehistory_id = get_current_pricehistory_id(place_id)
        estimated_time = calculate_estimated_time(activation_time, cost, place_id)
        pay = Payment(car_number, cost, estimated_time, transaction, place_id, pricehistory_id)
        pay.activation_time = activation_time
        db_session.add(pay)
        db_session.commit()
    return "all payments ok"
Ejemplo n.º 4
0
Archivo: talons.py Proyecto: zg/talons
    def on_post(self, req, resp):
        url = req.get_param('url')
        if url is not None:
            # generate a new job ID, insert it into the database, return the job ID to the client
            new_id = _generate_id()
            priority = req.get_param('priority') if req.get_param('priority') is not None else 3
            db_session.add(Job(id=new_id,status='INCOMPLETE',url=url,priority=priority,result=''))
            db_session.commit()

            # immediately tell them the job ID
            resp.data = json.dumps({'job-id':new_id})
            resp.status = falcon.HTTP_200

            # in the event that more than one requests are submitted before
            # we get to this point, this means the scraper will decide which
            # one to work with first

            # look for the most important job to do next
            next_job = db_session.query(Job).filter(Job.status == 'INCOMPLETE').order_by(desc(Job.priority),desc(Job.created)).first()
            if next_job is not None:
                # set the job as in-progress
                db_session.query(Job).filter(Job.id == next_job.id).update({"status":'IN_PROGRESS'})
                try:
                    # get the data, timeout at 30 minutes
                    response = urllib2.urlopen(next_job.url,timeout=30*60)
                    # submit the results to the database
                    db_session.query(Job).filter(Job.id == next_job.id).update({"result":response.read(),"status":'COMPLETED'})
                except urllib2.URLError, e:
                    # Python 2.6
                    if isinstance(e.reason, socket.timeout):
                        db_session.query(Job).filter(Job.id == next_job.id).update({"status":'INCOMPLETE'})
                    else:
                        # reraise the original error
                        raise
Ejemplo n.º 5
0
def create_SMSHistory_record(sms_id, site_service_id):
    try:
        sms = SMSHistory(sms_id, site_service_id)
        db_session.add(sms)
        db_session.commit()
    except AttributeError:
        raise AttributeError
Ejemplo n.º 6
0
def database():

	#check if user is in database
	if ( User.query.filter(User.email == request.form['email']).count() > 0):
		return "already recorded"

	#else, new user
	us = User(request.form['fullname'], request.form['email'])
	db_session.add(us)
	db_session.commit()

	#Get Message
	subject = 'Welcome to Papaya'
	message = "Hello "+ request.form['givenname'] + "!\n\n We're so glad you signed up for our alpha service. This is the humble start of an incredibly simple way to make your calendar data useful, so you can learn about and adapt to how you spend time. Over the course of the coming year, we will be rolling out a series of amazing features and will periodically keep you updated. \n\n Carpe Diem!\n- Papaya Team \n\n"
	name = request.form['fullname']
	address = request.form['email']

	#sent email
	requests.post(
		"https://api.mailgun.net/v2/sandbox371c5172c8984738b35884a88e2fc92b.mailgun.org/messages",
		auth=("api", "key-b90954e35d130bce6ed45af6fe5b795a"),
		data={"from": "Papaya App <*****@*****.**>",
					"to": name+" <"+address+">",
					"subject": subject,
					"text": message})

	return 'Welcome Email Sent'
Ejemplo n.º 7
0
def create_club():
    if not check_auth(request):
        abort(403)
    idclub = "0"
    name = ""
    description = ""
    if not request.json or not 'name' in request.json:
        abort(400)
    if not request.json or not 'description' in request.json:
        abort(400)
    if 'idclub' in request.json:
        idclub = request.json['idclub']
    if 'name' in request.json:
        name = request.json['name']
    if 'description' in request.json:
        description = request.json['description']
    club = Club(name=name, description=description)
    if str(idclub) != "0":
        db_session.query(Club).filter_by(idclub=int(idclub)).update({"name": name, "description": description})
        db_session.commit()
    else:
        db_session.add(club)
        db_session.commit()

    return jsonify({"status": "OK"})
Ejemplo n.º 8
0
	def post(self):
		try:
			args = self.reqparse.parse_args()

			email = args['email']
			query = db_session.query(models.User).filter(models.User.email == email)
			user = query.one_or_none()

			if user is not None:
				current_app.logger.warning("Already register id : " + email)
				return Response.error(error_code.Login.ALREADY_REGISTER)

			new_user = models.User(code=generate_uuid(), email=email, password_hash=sha256_crypt.encrypt(str(args['password'])), user_name=args['user_name'], role_id=args['role'],
								   room=args['room'], phone=args['phone'])
			db_session.add(new_user)
			db_session.commit()

			current_app.logger.info("Register new user : "******"/auth/confirm/" + generate_uuid()

			confirm = models.Confirm(email=email, type=models.Confirm_type.CONFIRM_REGISTER.name, url=url)
			db_session.add(confirm)
			db_session.commit()

			mail.make_confirm_email(email, url)

			return Response.ok()

		except Exception as e:
			current_app.logger.error(str(e))
			return Response.error(error_code.Global.UNKOWN)
Ejemplo n.º 9
0
def addOpenedPuzzle():
    result = dict(
        type=ProtocolTypes.AddPuzzle,
        result=ResultCodes.Success
        )

    # writeDirtyLog(request.form['data'])

    if request.form['data']:
        got_data = json.loads(request.form['data'])
        from_keys = [
            'session_id',
            # 'puzzle_index', 'opened'
        ]
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])

            if got_user:
                find_puzzle = OpenedPuzzle.query.filter_by(
                    user_id=got_user.id, puzzle_index=got_data['puzzle_index']).first()
                if find_puzzle:
                    find_puzzle.opened = got_data['opened']
                    db_session.add(find_puzzle)
                else:
                    made_puzzle = OpenedPuzzle(
                        got_user.id, got_data['puzzle_index'], got_data['opened'])
                    db_session.add(made_puzzle)

                result['result'] = commitData()
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError

    return str(json.dumps(result))
Ejemplo n.º 10
0
def setOwnCostumebases():
    result = {'type': ProtocolTypes.SetOwnCostumeBases}

    if request.form['data']:
        got_data = json.loads(request.form['data'])
        from_keys = ['session_id', 'own_costumebases']
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])

            if got_user:
                if got_data['own_costumebases'] == '':
                    result['result'] = ResultCodes.InputParamError
                else:
                    for got_costumebase_index in got_data['own_costumebases']:
                        find_costumebase = OwnCostumebase.query.filter_by(
                            user_id=got_user.id, costumebase_index=got_costumebase_index).first()
                        if not find_costumebase:
                            temp_costumebase = OwnCostumebase(got_user.id, got_costumebase_index)
                            db_session.add(temp_costumebase)
                    result['result'] = commitData()
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError

    return str(json.dumps(result))
Ejemplo n.º 11
0
def login():
    user = get_user()
    if user:
        return make_response(json.dumps(user.serialize()))

    if request.json:
        facebook_data = request.json
        user_id = facebook_data["userID"]
        access_token = facebook_data["accessToken"]
        user_details = json.loads(urllib.urlopen("https://graph.facebook.com/me?access_token=" + access_token).read())
        # login successful
        if user_details["id"] == user_id:
            user = User.query.filter(User.email == user_details["email"]).scalar()
            if not user:
                user = User(
                    email = user_details["email"],
                    first_name = user_details["first_name"],
                    last_name = user_details["last_name"],
                    username = user_details["username"],
                    facebook_id = user_details["id"],
                    facebook_url = user_details["link"],
                    access_token = facebook_data["accessToken"]
                )
            else:
                user.access_token = facebook_data["accessToken"]

            db_session.add(user)
            set_user(user)
            return make_response(json.dumps(user.serialize()))
        else:
            raise Exception("Error in logging in.")
    else:
        raise Exception("No login data or user logged in.")
Ejemplo n.º 12
0
def setWornCostume():
    result = dict(
        type=ProtocolTypes.SetWornCostume,
        result=ResultCodes.Success)

    if request.form['data']:
        got_data = json.loads(request.form['data'])
        from_keys = ['session_id', 'costumes']
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])

            if got_user:
                find_worn_costume = WornCostume.query.filter_by(user_id=got_user.id).first()
                if find_worn_costume:
                    find_worn_costume.costumes = json.dumps(got_data['costumes'])
                    db_session.add(find_worn_costume)
                else:
                    made_worn_costume = WornCostume(user_id=got_user.id, costumes=json.dumps(got_data['costumes']))
                    db_session.add(made_worn_costume)

                result['result'] = commitData()
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError


    return str(json.dumps(result))
Ejemplo n.º 13
0
def updatebyemail():
    jsonData = request.get_json(force=True)
    emailaddress = str(jsonData['address'])
    fname = (jsonData['fname']).encode("utf8")
    lname = (jsonData['lname']).encode("utf8")

    if len(fname)>40:
        return  jsonify(respo='First name to long')
    if len(lname)>40:
        return  jsonify(respo='Last name to long')
    if len(emailaddress)>40:
        return jsonify(respo='Email too long', emailaddress = emailaddress)
    user_exists = db_session.query(User).filter(User.email == emailaddress)
    if user_exists.count()==0:
        user = User(email = emailaddress, first_name = fname.decode("utf8"), last_name = lname.decode("utf8"), new_features_subscription=True)
        db_session.add(user)
        db_session.commit()
        return jsonify(respo='Subscription saved', )
    else:
        user_exists = user_exists.first()
        if user_exists.new_features_subscription==False:
            user_exists.new_features_subscription = True
            db_session.add(user_exists)
            db_session.commit()
            return jsonify(respo='Subscription saved', )
        else:
            return jsonify(respo='Subscription already exist', )
Ejemplo n.º 14
0
def add_record():
    try:
        lines = request.data.decode('utf-8').split('\n')
        secret = lines[0]
        if secret != app.config['IOT_SECRET']:
            return __forbidden()

        del lines[0:1]

        for timestamp_line in lines:
            pieces = timestamp_line.split(',')
            if len(pieces) < 2:
                return __bad_request()

            timestamp = pieces[0]
            arduino_uuid = pieces[1]  # TODO: Add to DB

            for piece in pieces[2:]:
                obj = extract_object_from_arduino_piece(piece, timestamp,
                                                        arduino_uuid)
                if obj:
                    db_session.add(obj)

        db_session.commit()
        return 'ok', 200
    except Exception as e:
        print(e)
        return __bad_request()
Ejemplo n.º 15
0
def addCategory():
  cat = Category(request.form['name'])
  db_session.add(cat)
  db_session.commit()
  status = True
  categories = getCategories()
  return render_template('admin.html', categories = categories, status = status, action='added')
Ejemplo n.º 16
0
def addDiagnoseComment():
    form = CommentsForm(request.form)
    resultForm=form.validate()
    if resultForm.status==rs.SUCCESS.status:
        #session['remember_me'] = form.remember_me.data
        # login and validate the user...
        diagnoseComment=Comment(form.userId,form.receiverId,form.diagnoseId,form.content)
        db_session.add(diagnoseComment)
        db_session.commit()
        db_session.flush()
        score=constant.DiagnoseScore[form.score]
        diagnose=Diagnose.getDiagnoseById(form.diagnoseId)
        diagnose.score=form.score
        Diagnose.save(diagnose)
        #为医生添加一些冗余字段
        if hasattr(diagnose,'doctor'):
            doctor=diagnose.doctor
            if score!=0:
                if doctor.goodFeedbackCount:
                    doctor.goodFeedbackCount+=1
                else:
                    doctor.goodFeedbackCount=1
            if doctor.feedbackCount:
                doctor.feedbackCount+=1
            else:
                doctor.feedbackCount=1
            Doctor.save(doctor)
        #flash('成功添加诊断评论')
        return jsonify(rs.SUCCESS.__dict__)
    return jsonify(rs.FAILURE.__dict__)
Ejemplo n.º 17
0
def register():
    if request.method == 'POST':
        if "" in request.form.values():
            return render_template("register.html")
        if request.form['username'] in list(User.query.values(User.name)):
            return render_template("register.html",error="Please enter a password.")
        if request.form['email'] in list(User.query.values(User.email)):
            return render_template("register.html",error="Please enter a valid email.")
        if request.form['password'] != request.form['passwordconfirm']:
            return render_template("register.html",error="Passwords do not match.")
        #TODO: error for when they try to register when logged in already
        u = User(request.form['username'], request.form['email'],generate_password_hash(request.form['password'].strip()))
        db_session.add(u)
        db_session.commit()

        for currency in config.get_currencies():
            addr = generate_deposit_address(currency)
            a = Address(currency,addr,u.id)
            db_session.add(a)
        db_session.commit()
        if not send_confirm_email(u.id):
            return home_page("ltc_btc", danger='An error occured during registration. Please contact the administrator.')
        return home_page("ltc_btc", dismissable='Successfully registered. Please check your email and confirm your account before logging in.')

    if request.method == 'GET':
        return render_template("register.html")
Ejemplo n.º 18
0
    def test_addAllRole(self):
        from DoctorSpring.models.user import Role,UserRole
        role=Role()
        role.id=1
        role.roleName='fenzhen'
        session.add(role)

        role=Role()
        role.id=2
        role.roleName='doctor'
        session.add(role)

        role=Role()
        role.id=3
        role.roleName='patient'
        session.add(role)

        role=Role()
        role.id=4
        role.roleName='hospitalUser'
        session.add(role)

        role=Role()
        role.id=6
        role.roleName='kefu'
        session.add(role)



        session.commit()
        session.flush()
Ejemplo n.º 19
0
def init_user_act():
	for i in range(10):
		usr = User(email='email#'+str(i), username='******'+str(i), password=str(i))
		acti = Activity(content='act#'+str(i))
		db_session.add(usr)
		db_session.add(acti)
	db_session.commit()
Ejemplo n.º 20
0
def add_video():
    playlist_id = request.form.get("playlist_id")
    if playlist_id.strip() == "":
        return jsonify({'error': "You must specify a playlist ID for this video."})

    playlist = Playlist.query.get(playlist_id)
    if playlist == None:
        return jsonify({'error': "Playlist not found"})

    slug = request.form.get("slug")
    if slug.strip() == "":
        return jsonify({'error': "You must specify a slug for this video."})

    thumbnail_url = request.form.get("thumbnail_url")
    if thumbnail_url.strip() == "":
        return jsonify({'error': "You must specify a thumbnail for this video."})

    title = request.form.get("title")
    if title.strip() == "":
        return jsonify({'error': "You must specify a title for this video."})

    v = Video(playlist_id, slug, thumbnail_url, title)
    db_session.add(v)
    db_session.commit()    

    # Publish to Redis so that all clients update playlist
    data = {
        "action": "update_playlist",
        "playlist": Playlist.get_videos(playlist_id)
    }

    redis.publish(playlist_id, json.dumps(data))

    return jsonify({"success": True})
Ejemplo n.º 21
0
def update_slide():
    """
    Updates a slide.
    """
    current_app.logger.debug("debug updateSlide")
    message = isValidURL(request.form['url'])
    if message is not None:
        return render_template(
            'admin.html',
            categories=category_controller.list(),
            status=False,
            message=message
        )
    if not request.form['screenshot']:
      screenshot = "img/badge-reserved.jpg"
    else:
      screenshot = request.form['screenshot']
    slide_id = request.form['id']
    s = SlideModel.query.get(slide_id)
    s.title = request.form['title']
    s.description = request.form['description']
    s.url = request.form['url']
    s.category = request.form['categorie']
    s.screenshot = screenshot
    db_session.add(s)
    db_session.commit()
    status = True

    return render_template(
        'admin.html',
        categories=category_controller.list(),
        status=status,
        action='updated'
    )
Ejemplo n.º 22
0
def _update_and_store_transcription_metadata(t, request):
    if request.values.get("biblio_id", ""):
      try:
        biblio_id = int(request.values.get("biblio_id"))
        b = Biblio.query.get(biblio_id)
        if b:
          t.biblio = b
      except ValueError as e:
        pass

    user_id = session['logged_in_user']
    u = User.query.get(user_id)

    raw = request.values.get("raw", "")
    if raw:
      t.raw = raw
    text = request.values.get("text", "")
    if text:
      t.text = text

    t.edited = u
    t.pagestart = request.values.get("pagestart", "0")
    t.pageend = request.values.get("pagestart", "0")
    t.volume = request.values.get("volume", "")[:29]
    t.article_title = request.values.get("article_title", "")[:69]

    db_session.add(t)
    db_session.commit()
Ejemplo n.º 23
0
def setButtonState():
    result = dict(
        type=ProtocolTypes.SetButtonState,
        result=ResultCodes.Success)

    if request.form['data']:
        got_data = json.loads(request.form['data'])
        from_keys = ['session_id', 'button']
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])

            if got_user:
                find_button = Button.query.filter_by(
                    user_id=got_user.id).first()
                if find_button:
                    find_button.state = got_data['button']
                    db_session.add(find_button)
                else:
                    made_button = Button(got_user.id, got_data['button'])
                    db_session.add(made_button)

                result['result'] = commitData()
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError

    return str(json.dumps(result))
Ejemplo n.º 24
0
def addDiary():
    result = dict(
        type=ProtocolTypes.AddDiary,
        result=ResultCodes.Success
    )

    # writeDirtyLog(request.form['data'])

    if request.form['data']:
        got_data = json.loads(request.form['data'])
        from_keys = [
            'session_id', 
            # 'diary_index'
        ]
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])

            if got_user:
                find_diary = Diary.query.filter_by(
                    user_id=got_user.id, diary_index=got_data['diary_index']).first()
                if find_diary:
                    result['result'] = ResultCodes.DataExist
                else:
                    made_diary = Diary(got_user.id, got_data['diary_index'])
                    db_session.add(made_diary)
                    result['result'] = commitData()
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError

    return str(json.dumps(result))
Ejemplo n.º 25
0
def upload_file(board, post_id=None):
    # Create the post
    post = models.Post(subject=request.form.get('subject'),
                       comment=request.form.get('comment'),
                       parent_id=post_id)
    db_session.add(post)
    db_session.flush()

    # Upload the file if present
    f = request.files['file']

    if f.filename:
        extension = get_extension(f)
        filename = "{0}.{1}".format(post.generate_filename(), extension)
        path = "{0}/static/{1}".format(app.root_path, filename)

        f.save(path)

        post.filename = filename
        post.mimetype = f.mimetype

    db_session.commit()

    # Redirect to page or post
    if post_id:
        return redirect(url_for('reply', board=board, post_id=post_id))
    else:
        return redirect(url_for('page', board=board))
Ejemplo n.º 26
0
def set_album(): 
	this_user_id=1
	album_name='西藏游'
	place = "西藏"
	album_type ="album"
	error=None
	error = checklogin()
	if album_name:
		if not place:
			album_place = ""
		else:
			album_place = place

		if not os.path.isdir(ALBUM_FOLDER+str(this_user_id)):
			os.makedirs(ALBUM_FOLDER+str(this_user_id))

		new_album = Album(this_user_id, album_name, place, album_type)
		db_session.add(new_album)
		db_session.commit()
		os.makedirs(ALBUM_FOLDER+str(this_user_id)+"/"+str(new_album.id))
		#创建成功

	else:
		session['error'] = "请填写相册名称"

	if 'error' in session:
		result = session['error']
		session.pop('error',None)
	return jsonify(error=error)
Ejemplo n.º 27
0
def getCodes():
    aid  = int(request.args.get('article'))
    l_i  = 0

    try:
        ## load current values
        curr = db_session.query(CodeFirstPass).filter_by(coder_id = current_user.id, article_id = aid).all()
        cd   = {}

        for c in curr:
            ## these will occur only once
            if c.variable in sv:
                cd[c.variable] = c.value
            else:
                ## if they've seen this article before, note which pass it is
                if c.variable == 'load':
                    l_i = int(c.value) + 1

                ## stash in array
                if c.variable not in cd:
                    cd[c.variable] = []

                cd[c.variable].append( [c.value, c.text] )

        ## insert row for every time they load the article
        ## to measure how much time it takes to read the article
        load = CodeFirstPass(aid, "load", l_i, current_user.id)
        db_session.add(load)
        db_session.commit()

        return jsonify(cd)
    except:
        return make_response("", 404)
Ejemplo n.º 28
0
def new_user():
	"""Display new user creation form or accept and process it"""
	require_auth('admin')

	if not ldap_up():
		return render_response('message.html',dict(
			message_type='error',
			title="Add New User - LDAP Problem",
			message="Cannot add a new user since LDAP is not accessible"
		))

	form = NewUserForm()

	if request.method == 'POST':
		values = request.form.copy()
		del values['_csrf_token']
		form.set(values)

		if form.validate():
			user = User(**(form.value))
			sess.add(user)
			sess.commit()
			flash('Successfully added new user')
			return redirect(url_for('display_user',username=form['user_name'].value))
		else:
			flash('Form Validation Failed','error')

	return render_response('add_user.html', dict(form=form,submit_url=url_for('new_user')))
Ejemplo n.º 29
0
def requestFriend():
    result = dict(
        type=ProtocolTypes.RequestFriend,
        result=ResultCodes.Success)

    if request.form['data']:
        got_data = json.loads(request.form['data'])

        from_keys = ['session_id', 'request_friend']
        if checkContainKeys(from_keys, got_data):
            result['result'], got_user = checkSessionId(got_data['session_id'])

            if got_user:
                find_friend = Friend.query.filter_by(user_id=got_user.id, friend_id=got_data['request_friend']).first()
                if not find_friend:
                    friend_data = Friend(got_user.id, got_data['request_friend'])
                    db_session.add(friend_data)
                    write_mail = Mail(got_user.id, got_data['request_friend'], u"친구 신청")
                    write_mail.request_friend = True
                    db_session.add(write_mail)
                    result['result'] = commitData()
                else:
                    result['result'] = ResultCodes.DataExist
        else:
            result['result'] = ResultCodes.InputParamError
    else:
        result['result'] = ResultCodes.AccessError

    return str(json.dumps(result))
Ejemplo n.º 30
0
def create_company():
    company = Company()
    company_data = json.loads(request.data)
    update_company_data(company, company_data)
    db_session.add(company)
    db_session.commit()
    return jsonify(company.to_dict())
Ejemplo n.º 31
0
def admin_dashboard_book_add():
    genres = Genre.query.all()
    languages = Language.query.all()
    authors = Author.query.all()
    if request.form:
        book = Book(
            title=request.form.get('title'),
            author=request.form.get('author'),
            genre=request.form.get('genre'),
            language=request.form.get('language'),
            summary=request.form.get('summary'),
        )
        db_session.add(book)
        db_session.commit()
        flash('Book successfully added')
        return redirect(url_for('admin_dashboard'))
    return render_template('/admins/book_add.html',
                           genres=genres,
                           languages=languages,
                           authors=authors)
Ejemplo n.º 32
0
    def auto_add(self, collection, document):
        """ insert a document in an auto increment table

            arguments:
                collection -- string name of the collection (or table)
                document -- the document in JSON format to be inserted

            returns:
                the record_id
        """
        table_ = getattr(db, collection)
        entry = table_(document)
        try:
            db_session.add(entry)
            res = db_session.commit()
            self.log.debug("New event")
            return True
        except Exception, e:
            self.log.error("database commmit error: {0}".format(e))
            return False
Ejemplo n.º 33
0
def get_problem():
    """returns a test Problem"""
    problem_type_args, problem_type = get_problem_type()
    PROBLEM_ARGS = {
        "problem_type": problem_type,
        "slug": "ioprob",
        "name": "The Input/Output Problem",
        "problem_statement": "Print the string 'Hello, World!' n times",
        "sample_input": "3",
        "sample_output": "Hello, World!Hello, World!Hello, World!",
        "secret_input": "4",
        "secret_output":
        "Hello, World!Hello, World!Hello, World!Hello, World!",
    }

    problem = model.Problem(**PROBLEM_ARGS)
    db_session.add(problem)
    db_session.commit()

    return PROBLEM_ARGS, problem
Ejemplo n.º 34
0
def start_before(date_before):
    # 获取日期内容
    url = 'https://news-at.zhihu.com/api/4/news/before/{}'.format(date_before)
    loop = asyncio.get_event_loop()
    task = asyncio.ensure_future(get_json_data(url))
    loop.run_until_complete(task)
    json_data = task.result()
    date = json_data['date']
    day_query = Day.query.filter_by(date=date)
    # 日期内容写入数据库
    if day_query.count() == 0:
        new_day = Day(date=date, data=json.dumps(json_data), update=datetime.now())
        db_session.add(new_day)
        db_session.commit()
    else:
        day_query.update({'data': json.dumps(json_data), 'update': datetime.now()})

    # 异步抓取文章
    tasks = [start_article(story, date) for story in json_data['stories']]
    loop.run_until_complete(asyncio.wait(tasks))
Ejemplo n.º 35
0
def notes():
    if request.method == "GET":
        query = request.args.get("query", None)
        if query is None:
            notes_from_db = Note.query.all()
        else:
            notes_from_db = Note.query.filter(or_(Note.title.contains(query), Note.content.contains(query))).all()
        result = []
        for note in notes_from_db:
            result.append(note.serialize)
        return jsonify(result)

    elif request.method == "POST":
        request_json = request.json
        content = request_json["content"]
        title = request_json.get("title", content[:min(N, len(content))])
        new_note = Note(title=title, content=content)
        db_session.add(new_note)
        db_session.commit()
        return jsonify(new_note.serialize)
Ejemplo n.º 36
0
def process_notify(payment_id):
    ticket = Ticket.query.filter(Ticket.payment_id == payment_id).first()

    if (ticket):
        if ticket.tariff == 20:
            message = "BRNO20"

        if ticket.tariff == 29:
            message = "BRNO"

        smska = PhoneSMS(phone="90206", message=message)

        smska.smstype = "send"

        smska.state = "waiting"

        smska.payment_id = ticket.payment_id

        db_session.add(smska)
        db_session.commit()
Ejemplo n.º 37
0
def main():
    today = strftime('%Y%m%d')
    batch_name = 'Jobs_Data_%s.csv' % today

    # Mark all current jobs_data batches inactive
    db_session.query(Batch).filter_by(datasource_id=6).update(
        {'is_active': False})
    batch = Batch(datasource_id=6, name=batch_name, is_active=True)
    db_session.add(batch)
    db_session.flush()
    db_session.commit()

    categories = range(1, 34)
    for c in categories:
        print "processing category %s" % c
        data = get_job_stats(c)
        push_to_hadoop(data, batch_name, c)
        push_to_sql(data['response']['cities'], batch.batch_id, c)

    db_session.close()
Ejemplo n.º 38
0
def addRack():
    '''
    Добавление стойки
    :return:
    '''

    if not request.json or not request.json['size']:
        return jsonify({'message': 'Error: need size'})

    size = RbSize.query.filter(RbSize.value == request.json['size']).first()
    if size:
        try:
            db_session.add(Rack(size.id))
            db_session.commit()
            return getMessage('Rack created.')
        except:
            return getMessage('Error creation of rack')
    else:
        return getMessage('Error: size with value %s not found' %
                          request.json['size'])
Ejemplo n.º 39
0
def project(project_id):

    form = ContactForm()

    if form.validate_on_submit():
        new_contact = Contact(project_id=project_id,
                              name=form.name.data,
                              link=form.link.data,
                              notes=form.notes.data,
                              in_contact=bool(form.in_contact.data),
                              active=bool(0))
        db_session.add(new_contact)
        db_session.commit()
        return redirect(url_for('main.project', project_id=project_id))

    contact_id = request.form.get('id')

    if request.form.get('update'):
        contact = db_session.query(Contact).get(contact_id)
        today = date.today()
        contact.checked = today
        db_session.commit()
    if request.form.get('edit'):
        return redirect(
            url_for('main.edit_contact',
                    contact_id=contact_id,
                    project_id=project_id))

    queued_contacts = (db_session.query(Contact).filter(
        Contact.project_id == project_id).filter(
            Contact.in_contact == 'false').all())
    current_contacts = (db_session.query(Contact).filter(
        Contact.project_id == project_id).filter(
            Contact.in_contact == 'true').all())
    project = (db_session.query(Project).filter(
        Project.project_id == project_id).first())
    return render_template('project.html',
                           queued_contacts=queued_contacts,
                           current_contacts=current_contacts,
                           project=project,
                           form=form)
Ejemplo n.º 40
0
def signup():
    error = None
    if request.method == 'POST':
        file = None
        filename = None
        if 'file' in request.files:
            file = request.files['file']
        name = request.form['name']
        email = request.form['email']
        password = (request.form['password'])
        confirm_password = (request.form['confirm-password'])
        manager = request.form.get('toggle-manager')
        canvasser = request.form.get('toggle-canvasser')
        # ALready catched all fields, then check it!!!!
        if dup_user(email):
            flash("The user already exists, please create new account!")
            return redirect(url_for('auth.home', index=1))
        if (password != confirm_password):
            flash("Please match the password before signup!")
            return redirect(url_for('auth.home', index=1))
        if not (manager == 'yes' or canvasser == 'yes'):
            flash("Please select at least one account type!")
            return redirect(url_for('auth.home', index=1))
        #Everthing is valid.  Create this user to DB
        if file and file.filename != '' and allowed_file(file.filename):
            app = current_app._get_current_object()
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        ps = generate_password_hash(password)
        new_user = User(email, ps, name, filename)
        db_session.add(new_user)
        db_session.commit()
        if manager == 'yes':
            role = Role('manager')
            new_user.users_relation.append(role)
        if canvasser == 'yes':
            role = Role('canvasser')
            new_user.users_relation.append(role)
        db_session.commit()
        flash("Create one new account Successfully!!")
    return redirect(url_for('auth.home', index=0))
Ejemplo n.º 41
0
def add_clar():
    """
    Adds a clarification

    Note:
        must be called from within a request context

    Returns:
        a redirect to the clarification view page
    """

    problem_input = request.form.get("problem")
    subject = request.form.get("subject")
    contents = request.form.get("contents")

    if subject is None:
        error = "Failed to add clarification due to undefined subject."
        current_app.logger.info(error)
        flash(error, "danger")
        return redirect(url_for("clarifications.clarifications_view"))

    if contents is None:
        error = "Failed to add clarification due to undefined contents."
        current_app.logger.info(error)
        flash(error, "danger")
        return redirect(url_for("clarifications.clarifications_view"))

    if (
            problem_input is None
    ):  # We check the problem input here because we can have a general clarification that would be a null problem in the database
        error = "Failed to add clarification due to undefined problem."
        current_app.logger.info(error)
        flash(error, "danger")
        return redirect(url_for("clarifications.clarifications_view"))

    problem = model.Problem.query.filter_by(name=problem_input).first()
    clar = model.Clarification(problem, current_user, subject, contents, False)
    db_session.add(clar)
    db_session.commit()

    return redirect(url_for("clarifications.clarifications_view"))
Ejemplo n.º 42
0
def ad_add():

    idcrag = request.form['idcrag'].strip()
    description = request.form['description'].strip()
    title = request.form['title'].strip()
    posting_time = request.form['posting_time'].strip()
    scheduled_action = request.form['scheduled_action'].strip()
    repost_timeout = request.form['repost_timeout'].strip()
    prev_action = ""
    prev_act_time = ""
    prev_act_stat = ""
    status = "Not posted"
    idusers = request.form['idusers'].strip()
    idcategory = request.form['category'].strip()
    idarea = request.form['area'].strip()
    replymail = None  #request.form['replymail']
    allowed_actions = "None,add"
    contact_phone = request.form['contact_phone'].strip()
    contact_name = request.form['contact_name'].strip()
    postal = request.form['postal'].strip()
    specific_location = request.form['specific_location'].strip()
    haslicense = request.form['has_license'].strip()
    license_info = request.form['license'].strip()

    a = Ad(idcrag, description, title, posting_time, scheduled_action,
           repost_timeout, prev_action, prev_act_time, prev_act_stat, status,
           idusers, idcategory, idarea, replymail, allowed_actions,
           contact_phone, contact_name, postal, specific_location, haslicense,
           license_info)

    db_session.add(a)

    try:
        db_session.commit()
    except Exception as e:
        db_session.rollback()
        logging.error("Application did not create " + a.__repr__() +
                      " becouse " + e.message)
        raise Exception('DB commit is not OK')

    return a.idads.__str__()
Ejemplo n.º 43
0
def add_testcase():
    if len(sys.argv) not in [3, 4]:
        print('usage: ./maintenance.py add_testcase <path_to_testcase> [-y]')
        sys.exit(1)
    with codecs.open(sys.argv[2], 'r', 'utf-8') as f:
        content = f.read()
    t = utils.parse_testcase(content)
    if len(sys.argv) == 4:
        assert sys.argv[3] == '-y'
    else:
        print(utils.testcase_to_text(t))
        confirm = raw_input('Confirm (y/n)? ')
        assert confirm.strip() == 'y'
    testcase = Testcase(enabled=True,
                        phase=t['phase'],
                        is_public=t['is_public'],
                        comment=t['comment'],
                        timeout=t.get('timeout', None),
                        cnt_run=0,
                        cnt_hack=0,
                        content=json.dumps(t))
    db_session.add(testcase)
    db_session.commit()

    tphase = utils.phase_to_index(testcase.phase)
    for compiler in db_session.query(Compiler):
        version = db_session.query(Version).filter(Version.id == compiler.latest_version_id).first()
        if not version:
            continue
        vphase = utils.phase_to_index(version.phase)
        if vphase > tphase or (vphase == tphase and version.status != 'pending'):
            r = TestRun(version_id=version.id,
                        testcase_id=testcase.id,
                        phase=testcase.phase,
                        status='pending',
                        created_at=datetime.utcnow())
            db_session.add(r)
            version.phase = testcase.phase
            version.status = 'running'
    db_session.commit()
    print('done!', sys.argv[2])
Ejemplo n.º 44
0
    def save(self):
        """Save the current form data an a new object."""
        question = self.model()

        for name, field in self._fields.items():
            if name != "choices":
                field.populate_obj(question, name)

        db_session.add(question)

        for choice_field in self._fields["choices"]:
            choice = Choice()
            choice_field.form.populate_obj(choice)
            question.choices.append(choice)

        try:
            db_session.commit()
        except IntegrityError as e:
            self.check_integrity_error(e)

        return question
Ejemplo n.º 45
0
def create_restaurant():
    if request.method == "POST":
        name = request.form.get('name')
        description = request.form.get('description')
        site_url = request.form.get('site_url')
        #inser data
        restaurants_entry = Restaurants(
                                    name= name,
                                    description = description,
                                    site_url = site_url

                    )
        db_session.add(restaurants_entry)
        db_session.commit()





        return redirect('/restaurants')
    return  render_template('create_restaurant.html')
Ejemplo n.º 46
0
    def test_user(self):
        """test the user table"""
        USER_ARGS = {
            "username": "******",
            "name": "Test A. B. User",
            "password":
            "******",
            "creation_time": util.str_to_dt("2017-01-01T12:12:00Z"),
            "misc_data": '{"teacher": "Cavanaugh"}',
        }

        # create and add user
        user = model.User(**USER_ARGS)
        db_session.add(user)
        db_session.commit()

        # fetch user
        results = model.User.query.filter_by(
            username=USER_ARGS["username"]).all()

        self.assertEqual(len(results), 1)
Ejemplo n.º 47
0
    def test_clarification(self):
        """test the clarification table"""
        contest_args, contest = get_contest()
        problem_args, problem = get_problem()
        user_args, user = get_user()

        CLARIFICATION_ARGS = {
            "problem": problem,
            "initiating_user": user,
            "subject": "Test subject",
            "contents": "What is this thing?",
            "is_public": False,
        }
        clarification = model.Clarification(**CLARIFICATION_ARGS)
        db_session.add(clarification)
        db_session.commit()

        results = model.Clarification.query.filter_by(
            subject=CLARIFICATION_ARGS["subject"]).all()

        self.assertEqual(len(results), 1)
Ejemplo n.º 48
0
    def test_run(self):
        """test the run table"""
        contest_args, contest = get_contest()
        problem_args, problem = get_problem()
        user_args, user = get_user()
        language_args, language = get_language()

        RUN_ARGS = {
            "user": user,
            "contest": contest,
            "language": language,
            "problem": problem,
            "submit_time": util.str_to_dt("2017-01-26T10:45:00Z"),
            "source_code": "print('hello'*input())",
            "run_input": "5",
            "correct_output": "hellohellohellohellohello",
            "is_submission": True,
        }
        run = model.Run(**RUN_ARGS)
        db_session.add(run)
        db_session.commit()
Ejemplo n.º 49
0
def registro():
    if request.method =='POST':
        POST_USUARIO = str(request.form['email'])
        POST_PWD = str(request.form['password'])
        POST_REPPWD = str(request.form['repPassword'])
        query = User.query.filter(User.username==POST_USUARIO)
        result = query.first()
        if POST_PWD != POST_REPPWD:
            flash(u'LAS CONTRASEÑAS NO COINCIDEN')
            return redirect(request.url)
        elif result:
            flash('YA EXISTE ESTE USUARIO')
            return redirect(request.url)
        else:
            user = User(POST_USUARIO,POST_PWD)
            db_session.add(user)
            db_session.commit()
            return redirect(url_for('login'))

    else:
        return render_template('registro.html')
Ejemplo n.º 50
0
def submit_project():
	# if not request.json:
	# 	abort(400)

	# if  not 'username' in request.jsonify:
	# 	abort(404)
	error = 'None'
	ID = uuid.uuid4().hex
	uname = request.json["username"]
	company = request.json['company']
	bu_name = request.json['bu']
	client = 	request.json['client']
	project = request.json['project']
	duration = 	request.json['duration']
	location = request.json['location']

	new_project = project_detail(id=ID, uname=uname, company=company, bu_name=bu_name, client=client, project=project, duration=duration, location=location)
	db_session.add(new_project)
	db_session.commit()

	return render_template('thank.html', error=error)
Ejemplo n.º 51
0
def get_user():
    """returns a test user"""
    USER_ARGS = {
        "email":
        "*****@*****.**",
        "name":
        "Test A. B. User",
        "password":
        "******",
        "creation_time":
        model.str_to_dt("2017-01-01T12:12Z"),
        "misc_data":
        '{"teacher": "Cavanaugh"}',
    }

    # create and add user
    user = model.User(**USER_ARGS)
    db_session.add(user)
    db_session.commit()

    return USER_ARGS, user
Ejemplo n.º 52
0
def login_session():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    username = request.form.get('username')
    password = request.form.get('password')
    if db_session.query(User).filter_by(username=username).count() == 1:
        user = db_session.query(User).filter_by(username=username).first()
        if user and user.verify_password(password):
            if not db_session.query(userStats).filter_by(
                    user_id=user.id).count():
                user_stats = userStats(user.id)
                db_session.add(user_stats)
            session.permanent = True
            app.permanent_session_lifetime = timedelta(days=5)
            session.modified = True
            login_user(user, remember=True)
            user.is_logged = True
            db_session.commit()
            return "OK"

    return abort(409)
Ejemplo n.º 53
0
def updateFollower(user, relatedUserId) :
    instaId = user['pk']
    userName = user['username']
    fullName = user['full_name']
    isPrivate = user['is_private']
    print ("USER: {0}".format(user))
    dbUser = InstaUser.query.filter_by(insta_id=instaId).first()
    if dbUser :
        print("User already processed, skip it.")
        return False
    else :
        dbUser = InstaUser()
        dbUser.insta_id = instaId
        dbUser.status = constant.USER_STATUS_NEW
        dbUser.user_id = relatedUserId
        dbUser.user_name = userName
        dbUser.full_name = fullName
        dbUser.is_private = isPrivate
        db_session.add(dbUser)
        db_session.commit()
    return True
Ejemplo n.º 54
0
def new_task():
    form = NewJobForm()

    if form.validate_on_submit():
        dest_address = form.dest_address.data
        message_subject = form.message_subject.data
        message_content = form.message_content.data

        new_job = EmailJob(dest_address=dest_address,
                           message_subject=message_subject,
                           message_content=message_content)

        db_session.add(new_job)

        db_session.commit()

        enqueue_send_email(new_job.id)

        return flask.redirect('/', code=302)

    return flask.render_template('new_job.html', form=form)
Ejemplo n.º 55
0
def create_user():
    data = request.get_json()

    if not all(key in data for key in ['login', 'password']):
        return jsonify(message='error'), 400

    user_login = data['login']
    password = data['password']

    if not 8 <= len(password) <= 72:
        return jsonify(message='error'), 400

    from models.user import User
    if User.query.filter(User.login == user_login).first() is None:
        pw_hash = bcrypt.generate_password_hash(password)
        user = User(user_login, pw_hash, False)
        db_session.add(user)
        db_session.commit()
        return jsonify(message='ok'), 200

    return jsonify(message='error'), 400
Ejemplo n.º 56
0
def store():
    '''Salva i dati del questionario nel db'''

    # Set up data to store
    data = dict(request.args)
    type = 'POST'
    age = None
    if data.get('history') == 'NA':
        type = 'PRE'
    if data.get('age') != '':
        age = data.put('age')

    survey = Survey(data.get('tag'), classtoken, type, data.get('path'),
                    data.get('history'), data.get('gender'), age,
                    data.get('residence'), data.get('q1'), data.get('q2'),
                    data.get('q3'), data.get('q4'), data.get('q5'),
                    data.get('q6'), data.get('q7'), data.get('q8'),
                    data.get('q9'), data.get('freetext'))
    db_session.add(survey)
    db_session.commit()
    return render_template('credits.html', type=type, path=data.get('path'))
def update_planning(uuid):
    req = request.get_json()

    if not req or 'planning' not in req:
        return _bad_request()

    try:
        planning = _get_planning(uuid, g.user_id)
    except CAPException as e:
        return e.res

    if not planning:
        return jsonify({'message':
                        'Planning with uuid "%s" not found' % uuid}), 404

    planning.planning_txt = req['planning']

    db_session.add(planning)
    db_session.commit()

    return jsonify({}), 202
Ejemplo n.º 58
0
def register():
    if request.method == 'POST':
        email = request.form['email']
        username = request.form['name']
        password = request.form['pass']
        password = generate_password_hash(password)
        try:
            new_user = User(username=username, password=password)
            db_session.add(new_user)
            db_session.commit()
        except:
            return jsonify({
                "status": "error",
                "message": "Could not add user"
            })
        return jsonify({
            "status": "success",
            "message": "User added successfully"
        }), 201

    return render_template('forms/signup.html')
Ejemplo n.º 59
0
def posts():
    try:
        feeds = models.Feed.query.all()
        for feed in feeds:
            url = feed.url
            data = parse_feed(url)
            for d in data:
                s = models.Song.query.filter_by(song_id=d['song_id']).first()
                if s is None:
                    song = models.Song(title=d['title'],
                                       player_id=d['player_id'],
                                       song_id=d['song_id'],
                                       feed_id=feed.id,
                                       pub_date=d['pub_date'])
                    db_session.add(song)
        db_session.commit()
        return "Success"
    except IntegrityError as e:
        pass
    except Exception as e:
        return "Error: " + str(e)
Ejemplo n.º 60
0
def code1Next():
    now     = dt.datetime.now(tz = central).replace(tzinfo = None)
    article = None

    while article == None:
        ## get next article in this user's queue
        next    = db_session.query(ArticleQueue).filter_by(coder_id = current_user.id, coded1_dt = None).first()

        ## out of articles, return null page
        if next is None:
            return render_template("null.html")

        article = db_session.query(ArticleMetadata).filter_by(id = next.article_id).first()

        ## this is a weird error and shouldn't happen but here we are.
        if article is None:
            next.coded1_dt = now
            db_session.add(next)
            db_session.commit()

    return redirect(url_for('code1', aid = next.article_id))