Пример #1
0
def create_blog_api():
    user = g.get('user', None)
    if user is None:
        return redirect(url_for('login'))
    else:
        if user.admin:
            name = request.form['name'].encode('utf8')
            summary = request.form['summary'].encode('utf8')
            content = request.form['content'].encode('utf8')
            user_id = request.form['user_id'].encode('utf8')
            user_name = request.form['user_name'].encode('utf8')
            user_image = request.form['user_image'].encode('utf8')
            sess = DBSession()
            blog = Blogs(user_id=user_id,
                         user_name=user_name,
                         user_image=user_image,
                         name=name,
                         summary=summary,
                         content=content)
            sess.add(blog)
            sess.commit()
            sess.close()
            return 'ok'
        else:
            return redirect(url_for('login'))
Пример #2
0
def oauth2callback(request):
    log.info('oauth2callback called at %s', request.url)

    # Get the auth code from the GET params
    try:
        code = request.GET['code']
        log.info('Successfully got auth code')
    except KeyError:
        log.error('Could not find auth code in GET params')
        return error_response(500, 'Sorry, but Google authorization failed.')

    # Exchange the auth code for a bearer/access token
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
                               redirect_uri=request.route_url('oauth2callback'))
    credentials = flow.step2_exchange(code)
    try:
        access_token = credentials.access_token
        refresh_token = credentials.refresh_token
        token_expiry = credentials.token_expiry
        if access_token is None or refresh_token is None or token_expiry is None:
            raise ValueError
    except (AttributeError, ValueError):
        log.error('Could not get access token, refresh token, and/or token expiry from exchanged credentials')
        return error_response(500, 'Sorry, but Google authorization failed.')
    DBSession.add(GDriveAccount(access_token, refresh_token, token_expiry))

    return Response('Successfully authorized with Google Drive!')
Пример #3
0
def post_entry(request):
	entry = m.Entry()
	entry.start_datetime = datetime.datetime.now()
	entry.updated_datetime = datetime.datetime.now()
	DBSession.add(entry)
	DBSession.flush()
	return entry.entry_id
Пример #4
0
    def job_output(self):
        log = logging.getLogger(__name__)

        jobid = self._request.matchdict['jobid']
        log.info('Request job output for id:{0}'.format(jobid))

        ssh_holder = self._request.registry.settings['ssh_holder']
        ssh_jobmanager = SSHBasedJobManager(ssh_holder)

        jobs = self._get_current_jobs(ssh_jobmanager, self._coltitles)
        joboutput = ssh_jobmanager.get_job_output(jobid)

        if 'error' in joboutput and joboutput['error'] is None:
            db_joboutput = JobOutput(id=jobid, output=jsonpickle.encode(joboutput))
            DBSession.add(db_joboutput)
            DBSession.commit()

        if 'error' in joboutput and joboutput['error'] is not None:
            jobresult = joboutput['error']
        else:
            jobresult = joboutput['content']
            jobresult = ''.join(jobresult)
        if 'type' not in joboutput:
            joboutput['type'] = 'type field missing'

        return {'project': self._projectname,
                'jobs': jobs,
                'output': dict(jobid=jobid, output=jobresult, type=joboutput['type'])}
Пример #5
0
    def filemonitoring(self):
        log = logging.getLogger(__name__)
        if self._request.params:
            # TODO: add this information to the file
            md5_enabled = True if 'withmd5' in self._request.params and self._request.params['withmd5'] == '0' else False
            all_files = self._request.params.getall('file')

            complete_file, filenames, folders = self._get_monitored_files(self._request.params['folder'] + '/')

            with transaction.manager:
                for f in all_files:
                    if f in complete_file:
                        log.debug('Skipping file {0}, because it is already monitored'.format(f))
                        continue
                    (path, filename) = os.path.split(f)
                    dbobj = MonitoredFile(path, filename, f)
                    DBSession.add(dbobj)
                DBSession.commit()
            files_not_mentioned = [c for c in complete_file if c not in all_files]
            # TODO: decide on this
            log.info('TODO: Still have to decide whether files which are not selected should be deleted or not.'
                     'Affected files would be: {0}'.format(files_not_mentioned))
        else:
            log.info('Got an empty request, going to redirect to start page')
            subreq = Request.blank('/')
            return self._request.invoke_subrequest(subreq)

        subreq = Request.blank(self._request.route_path('filebrowser'),
                               POST=dict(folder=self._request.params['folder'],
                                         currentfolder=self._request.params['currentfolder'],
                                         pathdescription='abs'))
        return self._request.invoke_subrequest(subreq)
Пример #6
0
 def on_set_base_info(cls, company_id, company_name=None, country=None, city=None, address=None, timezone=None,
                      currency=None, note=None):
     """ 设置公司基础信息 """
     session = DBSession()
     com = session.query(cls).filter(cls.company_id == company_id).first()
     if com:
         if company_name:
             com.company_name = company_name
         if country:
             com.country = country
         if city:
             com.city = city
         if address:
             com.address = address
         if timezone:
             com.timezone = timezone
         if currency:
             com.currency = currency
         if note:
             com.note = note
         try:
             session.add(com)
             session.commit()
         except Exception as why:
             session.rollback()
             message = "companies.on_set_base_info: {0}".format(why)
             logging.info(message)
             return -1
     return 0
Пример #7
0
    def _init(self, stmtrs):
        # BANKTRANLIST
        tranlist = stmtrs.find('BANKTRANLIST')
        if tranlist is not None:
            self.transactions = TransactionList(self.account, tranlist)
            DBSession.add_all(self.transactions)

        # LEDGERBAL - mandatory
        ledgerbal = stmtrs.find('LEDGERBAL')
        self.ledgerbal = ledgerbal.instantiate(acctfrom=self.account)
        DBSession.add(self.ledgerbal)

        # AVAILBAL
        availbal = stmtrs.find('AVAILBAL')
        if availbal is not None:
            self.availbal = availbal.instantiate(acctfrom=self.account)
            DBSession.add(self.availbal)

        ballist = stmtrs.find('BALLIST')
        if ballist:
            self.other_balances = [bal.instantiate() for bal in ballist]
            DBSession.add_all(self.other_balances)

        # Unsupported subaggregates
        for tag in ('MKTGINFO', ):
            child = stmtrs.find(tag)
            if child:
                stmtrs.remove
Пример #8
0
class LagouPipeline(object):
    def __init__(self):
        self.session = DBSession()
        self.pool = redis.Redis(host='raspberrypi', port=6379, db=2)

    def process_item(self, item, spider):
        if isinstance(item, LagouItem):

            if self.session.query(Jobs).filter(
                    Jobs.positionId == item['positionId'],
                    Jobs.companyId == item['companyId']).first():
                pass
            else:
                obj = Jobs(
                    companyId=item['companyId'],
                    positionId=item['positionId'],
                    jobNature=item['jobNature'],
                    companyName=item['companyName'],
                    financeStage=item['financeStage'],
                    companyFullName=item['companyFullName'],
                    companySize=item['companySize'],
                    industryField=item['industryField'],
                    positionName=item['positionName'],
                    city=item['city'],
                    createTime=item['createTime'],
                    salary_low=item['salary_low'],
                    salary_high=item['salary_high'],
                    workYear=item['workYear'],
                    education=item['education'],
                    positionAdvantage=item['positionAdvantage'],
                    district=item['district'],
                    # uid=item['uid'],
                    companyLabelList=item['companyLabelList'],
                )
                self.session.add(obj)
                try:
                    self.session.commit()
                except Exception, e:
                    print e
                    self.session.rollback()

        # self.session.close()

        elif isinstance(item, CompanyItem):
            # 公司信息存入mysql数据库
            '''
            obj=Company(
                companyId=item['companyId'],
                companyName=item['companyFullName']
            )
            self.session.add(obj)
            try:
                self.session.commit()
            except Exception, e:
                print e
                self.session.rollback()
            '''

            # 公司的数据存入redis
            self.pool.set(item['companyId'], item['companyFullName'])
Пример #9
0
def getUser(request):

    username = request.headers["X-Webauth-User"]
    #now get the uuid
    uuid = ""
    print "UserName:"******"UUID:", uuid

    if uuid == "":
        user = DBSession.query(Owners).filter_by(username=username).all()
    else:
        user = DBSession.query(Owners).filter_by(uuid=uuid).all()

    if len(user) == 0:
        cur = Owners(username, uuid)
        DBSession.add(cur)
        DBSession.commit()
        user = DBSession.query(Owners).filter_by(username=username).all()

        print "Made"

    if len(user) == 1:
        print "Found"
        cur = user[0]

    # if user == "zemon1":
    #     user = "******"

    return cur
Пример #10
0
def attach_pictures(request):
    menu_query = DBSession.query(Menu).filter(Menu.id==request.matchdict['menu_id'])
    images_id = menu_query.one().images_id
    images_id = images_id.split(' ') if images_id else []
    if images_id:
        images = DBSession.query(Image).filter(Image.id.in_(images_id)).all()
    added_thumbs = []
    if "data" in request.params:
        data = json.loads(request.params["data"])
        for image_info in data:
            image, thumb = image_info
            if not image or not thumb:
                continue
            ext = os.path.splitext(image)[-1].lower()
            if ext in (".jpg", ".jpeg", ".png"):
                new_image = Image(image_url=image, thumb_url=thumb)
                added_thumbs.append(thumb)
                DBSession.add(new_image)
                DBSession.flush()
                DBSession.refresh(new_image)
                images_id.append(new_image.id)
        menu_query.update({
                "images_id": ' '.join([str(i) for i in images_id]),
                })
    return json.dumps(added_thumbs)
Пример #11
0
def upload(request):
    if request.content_length/1000000 > 20:
        return error_response(400, 'Sorry, but the file must be under 20MB.')

    # Create photo object in database
    photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length)
    DBSession.add(photo)
    DBSession.flush()

    # Save uploaded file
    input_file = request.POST['file'].file
    input_file.seek(0)
    if not os.path.exists('data'):
        os.makedirs('data')
    if not os.path.exists('data/uploads'):
        os.makedirs('data/uploads')
    upload_path = os.path.join('data', 'uploads', str(photo.id))
    with open(upload_path, 'w') as f:
        shutil.copyfileobj(input_file, f)

    # Check the content type and rename as appropriate
    mime = magic.from_file(upload_path, mime=True)
    if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']:
        resp = Response('Sorry, but we can only accept jpg, gif, or png files.')
        resp.status_code = 400
        resp.status_string = '400 Bad Request'
        return resp
    extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg',
                 'image/gif': '.gif', 'image/png': '.png',
                 'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime]
    os.rename(upload_path, upload_path + extension)
    photo.content_type = mime

    return Response('OK')
Пример #12
0
def postAdd(request):
    
    currentUser = int(authenticated_userid(request))
    rankWeight = None #TODO
    pasteTitle = request.POST['paste_title']
    topic_id = request.POST['topic']
    
    newPost = Post(currentUser,rankWeight,topic_id,pasteTitle)
    DBSession.add(newPost)
    DBSession.flush()
    
    contentTitles = []
    contentURLs = []
    for key, value in request.POST.iteritems():
        if key == "title" and value != "":
            contentTitles.append(value)
        elif key == "URL" and value != "":
            contentURLs.append(value)
    
    contents = []
    for title,URL in zip(contentTitles,contentURLs):
        contentType = "LINK"  # TODO
        
        newContent = Content(title,URL,contentType,newPost.id)
        DBSession.add(newContent)
        DBSession.flush()
        
        contents.append(row2dict(newContent))
    
    post = {}
    post['post'] = row2dict(newPost)
    post['contents'] = contents
    
    return {'post' : post}
Пример #13
0
    def sentiment_data(self, url, common_list):
        """
        Does the sentiment analysis with wit.ai
        and saves the sentiment data into the database.
        """
        query_str = urllib.parse.quote_plus(' '.join(common_list)[:280])
        resp = yield self.fetch_url(
            'https://api.wit.ai/message?v=20180703&q={}'.format(query_str),
            headers={
                'Authorization':
                'Bearer {WIT_AUTH_KEY}'.format(WIT_AUTH_KEY=WIT_AUTH_KEY)
            })
        ents = json.loads(resp['body'])['entities']
        sentiment = ents and ents.get('sentiment')
        if sentiment:
            sentiment = sentiment[0]['value']
            s_obj = DBSession.query(UrlSentiment).filter(
                UrlSentiment.sentiment == sentiment)
            if s_obj.count() == 0:
                s_obj = UrlSentiment(url=url, sentiment=sentiment)
                DBSession.add(s_obj)
                DBSession.commit()

                raise gen.Return(s_obj)
        raise gen.Return(False)
Пример #14
0
    def instantiate(self, **extra_attrs):
        """ 
        Create an instance of a SQLAlchemy model class corresponding to
        my OFX tag, with attributes given by my contained OFX elements.

        If an instance that matches the given primary key signature has
        already been given, return that instead of creating a new one.
        """
        self.extra_attributes = extra_attrs
        # SECID needs to instantiate as SECINFO
        if self.tag == 'SECID':
            SubClass = models.SECINFO
        else:
            SubClass = getattr(models, self.tag)
        self._preflatten()
        self.attributes = self._flatten()
        self._postflatten()
        self.attributes.update(self.extra_attributes)
        self.extra_attributes = {}

        try:
            fingerprint = SubClass._fingerprint(**self.attributes)
            instance = DBSession.query(SubClass).filter_by(**fingerprint).one()
        except NoResultFound:
            instance = SubClass(**self.attributes)
            DBSession.add(instance)

        return instance
 def write_jobs_to_database(jobs):
     """
     Writes the retrieved jobs to the database
     :param jobs: list of all jobs
     :return:
     """
     log = logging.getLogger(__name__)
     with transaction.manager:
         for (classname, classmembers) in jobs.items():
             if len(classmembers) == 0:
                 continue
             for element in classmembers:
                 if 'error' in element:
                     continue
                 if 'JobID' not in element:
                     log.debug('Row didn''t match specified criteria {0}'.format(element))
                     continue
                 if not re.search('[0-9]*', element['JobID']):
                     log.debug('Row didn''t match specified criteria {0}'.format(element))
                     continue
                 dbrow = DBSession.query(Job).filter(Job.id == element['JobID']).all()
                 json_str = jsonpickle.encode(element)
                 if len(dbrow) == 0:
                     j = Job(element['JobID'], json_str)
                     DBSession.add(j)
                 elif len(dbrow) == 1:
                     dbrow[0].jobinfo = json_str
                 else:
                     log.error('More than one entry for jobid: {0}'.format(json_str))
         DBSession.commit()
Пример #16
0
 def __init__(self, stmtrs):
     """ Initialize with *STMTRS Element """
     self.currency = stmtrs.find('CURDEF').text
     acctfrom = stmtrs.find(self._acctTag)
     self.account = acctfrom.instantiate()
     DBSession.add(self.account)
     self._init(stmtrs)
Пример #17
0
def make_admin(config_path):
    from intranet3.models import User
    user_login = sys.argv[-1]
    if len(sys.argv) < 4:
        print u"Provide user login"
        return

    session = DBSession()

    user = session.query(User).filter(User.email == user_login).first()

    if not user:
        print u"No such user: %s" % user_login
        return

    if 'admin' in user.groups:
        print u'Removing %s from group admin' % user.name
        groups = list(user.groups)
        groups.remove('admin')
        user.groups = groups
    else:
        print u'Adding %s to group admin' % user.name
        groups = list(user.groups)
        groups.append('admin')
        user.groups = groups

    session.add(user)
    transaction.commit()
Пример #18
0
def make_admin(config_path):
    from intranet3.models import User
    user_login = sys.argv[-1]
    if len(sys.argv) < 4:
        print u"Provide user login"
        return

    session = DBSession()

    user = session.query(User).filter(User.email==user_login).first()

    if not user:
        print u"No such user: %s" % user_login
        return

    if 'admin' in user.groups:
        print u'Removing %s from group admin' % user.name
        groups = list(user.groups)
        groups.remove('admin')
        user.groups = groups
    else:
        print u'Adding %s to group admin' % user.name
        groups = list(user.groups)
        groups.append('admin')
        user.groups = groups

    session.add(user)
    transaction.commit()
Пример #19
0
def eventAdd(request):
    
    eventName = request.POST['name']
    eventType = request.POST['type']
    eventDescription = request.POST['description']
  
    image = request.POST.getall('file')
    for i in image:
	imageId = uuid.uuid1()
	imageUrl = str(imageId)
	open('/home/mohit/intern/hallwala/HallWala/hallwala/images/%d.jpg' % (imageId), 'wb').write(i.file.read())

    for infile in glob.glob("/home/mohit/intern/hallwala/HallWala/hallwala/images/*.jpg"):
        im = Image.open(infile)
	# don't save if thumbnail already exists
	if infile[0:2] != "T_":
	# convert to thumbnail image
		im.thumbnail((128, 128), Image.ANTIALIAS)
	        # prefix thumbnail file with T_
	        im.save("T_" + infile, "JPEG")



    newEvent = Event(eventName,eventType,eventDescription)
    DBSession.add(newEvent)
    DBSession.flush()
   
    event = newEvent.getJSON()
    return {'event' : event}
Пример #20
0
def crawl_plat_overview(first_letter):
    # url = "https://www.wdzj.com/dangan/pjs/"
    url = "https://www.wdzj.com/dangan/{first_letter}/".format(
        first_letter=first_letter
    )
    print("crawl plat {}".format(first_letter))
    response = requests.get(url, headers=HEADERS)
    if response.status_code != 200:
        print('crawl failed: code: {}, url: {}'.format(response.status_code, url))
        return
        # raise CrawlFailed('crawl failed!')
    encode_response(response)
    html = etree.HTML(response.text)
    try:
        plat_name = html.xpath("//div[@class='title']/h1|h2")[0].text
        print("plat name: {}".format(plat_name))
        # 注册资金(实缴资金) 银行存管 投标保障

        # box = html.xpath("//div[@class='zzfwbox'] | //div[@class='bgbox-bt zzfwbox']")
        try:
            zczj = html.xpath("//div[@class='zzfwbox']/dl[1]/dd[1]//div[@class='r']")[0].text.strip().split()
        except IndexError:
            zczj = html.xpath("// div[ @class ='bgbox-bt zzfwbox'] // dl[1] / dd[1] // div[@ class ='r']")[0].text.strip().split()
        # // div[ @class ='bgbox-bt zzfwbox'] // dl[1] / dd[1] // div[@ class ='r']
        if len(zczj) == 2:
            zczj_value, sjzj = zczj
            sjzj_value = sjzj.strip('()').split(':')[1]
        else:
            zczj_value = zczj
            sjzj_value = '-'

        try:
            yhcg_value = html.xpath("//div[@class='zzfwbox']/dl[1]/dd[2]//div[@class='r']")[0].text.strip()
        except IndexError:
            yhcg_value = html.xpath("//div[ @class ='bgbox-bt zzfwbox']//dl[1]/dd[2]//div[@class='r']")[0].text.strip()

        try:
            tbbz_value = html.xpath("//div[@class='zzfwbox']/dl[2]/dd[3]//div[@class='r']")[0].text.strip()
        except IndexError:
            tbbz_value = html.xpath("//div[ @class ='bgbox-bt zzfwbox']//dl[2]/dd[3]//div[@class='r']")[0].text.strip()

        plat_overview = dict(
            plat_name=plat_name,
            zhucezijin=zczj_value,
            shijiaozijin=sjzj_value,
            yinhangcunguan=yhcg_value,
            toubiaobaozhang=tbbz_value
        )
    except AttributeError as ex:
        print('crawl failed: ex: {}, url: {}'.format(str(ex), url))
        raise
    except IndexError as ex:
        print('crawl failed: ex: {}, url: {}'.format(str(ex), url))
        raise
    new_plat_overview = PlatOverview(**plat_overview)
    session = DBSession()
    session.add(new_plat_overview)
    session.commit()
    session.close()
 def save_data(self, data):
     session = DBSession()
     temp = data.copy()
     temp['timestamp'] = time()
     new_record = Data(**temp)
     session.add(new_record)
     session.commit()
     session.close()
Пример #22
0
def entity_type_put(request):
    dbsession = DBSession()
    entity_type = EntityType()
    entity_type.name = clean_matchdict_value(request, 'entity_type')
    entity_type.timestamp = get_timestamp()
    dbsession.add(entity_type)
    transaction.commit()
    return {'status': 'success'}
Пример #23
0
def signup(request):
    form = Form(request, schema=SignupSchema())
    if form.validate():
        user = form.bind(User())
        DBSession.add(user)
        request.session.flash(u'Now you can sign in', 'success')
        return HTTPFound(location=request.route_url('signin'))
    return _response_dict(request, renderer=FormRenderer(form))
Пример #24
0
def group(request):
    dbsession = DBSession()
    name = clean_matchdict_value(request, 'group')
    group = Group()
    group.name = name
    group.timestamp = get_timestamp()
    dbsession.add(group)
    transaction.commit()
    return {'status': 'success'}
Пример #25
0
def create_translation(client_id, contents=list(), gist_type='Service'):
    gist = TranslationGist(client_id=client_id, type=gist_type)
    DBSession.add(gist)
    DBSession.flush()
    for content in contents:
        atom = TranslationAtom(client_id=client_id, content=content[0], locale_id=content[1], parent=gist)
        DBSession.add(atom)
    DBSession.flush()
    return gist
Пример #26
0
def create_pad(request):
    form = Form(request, schema=PadSchema())
    if form.validate():
        pad = form.bind(Pad())
        pad.user = get_current_user(request)
        DBSession.add(pad)
        request.session.flash(u'Pad is successfully created', 'success')
        return HTTPFound(location=request.route_url('notes'))
    return _response_dict(request, renderer=FormRenderer(form), pad=False)
Пример #27
0
 def test_add_post(self):
     from models import Post
     with transaction.manager:
         post = Post("Hallo World!", "Hallo body World!")
         DBSession.add(post)
     post = Post.by_id(1)
     self.assertEqual(post.id, 1)
     self.assertEqual("Hallo World!", post.title)
     self.assertEqual("Hallo body World!", post.body)
 def write_job_archive_config(configuration):
     """
     Writes a new job archive configuration to the database
     :param configuration:
     :return:
     """
     with transaction.manager:
         DBSession.add(ArchiveUserConfiguration(jsonpickle.encode(configuration)))
         DBSession.commit()
Пример #29
0
 def setUp(self):
     self.config = testing.setUp()
     from sqlalchemy import create_engine
     engine = create_engine('sqlite://')
     from models import Base, MyModel
     DBSession.configure(bind=engine)
     Base.metadata.create_all(engine)
     with transaction.manager:
         model = MyModel(name='one', value=55)
         DBSession.add(model)
Пример #30
0
def add_money(player_in, amount):
    in_player = Player.query.filter(Player.id == int(player_in)).first()

    movement_in = Movement(player=in_player, amount=amount, move_type=Movement.TYPES['IN'])
    DBSession.add(movement_in)

    in_player.update_balance(operation_type=Movement.TYPES['IN'], amount=amount)

    DBSession.flush()
    DBSession.commit()
Пример #31
0
def subtract_money(player_out, amount):
    out_player = Player.query.filter(Player.id == int(player_out)).first()

    movement_out = Movement(player=out_player, amount=amount, move_type=Movement.TYPES['OUT'])
    DBSession.add(movement_out)

    out_player.update_balance(operation_type=Movement.TYPES['OUT'], amount=amount)

    DBSession.flush()
    DBSession.commit()
Пример #32
0
def action_put(request):
    dbsession = DBSession()
    action = Action()
    action.name = clean_matchdict_value(request, 'action')
    action.description = clean_param_value(request, 'description')
    action.points = clean_param_value(request, 'points')
    action.timestamp = get_timestamp()
    dbsession.add(action)
    transaction.commit()
    return {'status': 'success'}
Пример #33
0
def create_user(username, password):
    logging.debug("creating user %s" % (username))
    if find_user(username):
        raise RuntimeError("User %s already exists" % (username))
    hashed_password = hash_password(password)
    u = User(username=username, password=hashed_password)
    DBSession.add(u)
    DBSession.flush()
    DBSession.expunge(u)
    return u
Пример #34
0
def make_session(user, sessionid=None, expires_in=3600):
    if not sessionid:
        sessionid = str(uuid.uuid4())
    DBSession.query(Session).filter(Session.sessionid == sessionid).delete()
    logging.debug("making session for %s with sessionid %s" % (user.username, sessionid))
    s = Session(user_id=user.id, sessionid=sessionid, expires=datetime.datetime.now() + datetime.timedelta(0, expires_in))
    DBSession.add(s)
    DBSession.flush()
    DBSession.expunge(s)
    return s
Пример #35
0
def create_user(username, password):
    logging.debug("creating user %s" % (username))
    if find_user(username):
    	raise RuntimeError("User %s already exists" % (username))
    hashed_password = hash_password(password)
    u = User(username=username, password=hashed_password)
    DBSession.add(u)
    DBSession.flush()
    DBSession.expunge(u)
    return u
Пример #36
0
def add_players_command(num_of_players):
    '''num_of_players: Numero de jogadores'''
    for p in range(int(num_of_players)):
        player_name = 'Jogador {}'.format(p + 1)
        player = Player(player_name=player_name)
        DBSession.add(player)

    player = Player(player_name='Banqueiro', balance=float(1000000.00))
    DBSession.add(player)
    DBSession.flush()
    DBSession.commit()
Пример #37
0
 def post(self, catid):
     session = DBSession()
     args = parser.parse_args()
     if 'name' not in args.keys():
         abort(400, message="`name` missing")
     if len(args['name']) == 0:
         abort(400, message="`name` empty")
     category = session.query(models.Category).filter_by(id=catid).first()
     item = models.Item(category=category, name=args['name'])
     session.add(item)
     session.commit()
def addToLog(log_user,log_type,log_message):
    mySession = DBSession()
    newLog = Activitylog(log_user,log_type,log_message)
    try:
        transaction.begin()
        mySession.add(newLog) #Add the new log to MySQL
        transaction.commit()
        mySession.close()
    except:
        transaction.abort()
        mySession.close()
Пример #39
0
def create_user(request):
    data = json.loads(request.body)
    new_user = User(
        uid=data['username']
    )
    new_user.created_at = datetime.now()
    if DBSession.query(User).filter(User.name == new_user.name).count() > 0:
        raise HTTPUnauthorized()
    DBSession.add(new_user)
    DBSession.commit()
    return {"success": True}
def add(request):
    form = ReusableForm()
    if request.method == 'POST':
        name = request.params['name']
        lname = request.params['lname']
        age = request.params['age']
        address = request.params['address']
        DBSession.add(
            User(First_Name=name, Last_Name=lname, Age=age, Address=address))
        transaction.commit()
    users = DBSession.query(User).all()
    return dict(form=form, results=users)
Пример #41
0
 def add_record(self):
     """Verifies post form and saves record to database."""
     form_json = self.request.json
     with transaction.manager:
         record = Record.from_dict(form_json)
         DBSession.add(record)
         # refresh record before commit to send creted Record in response
         DBSession.flush()
         DBSession.refresh(record)
         response_json = record.to_json()
         transaction.commit()
     return Response(status=201, json=response_json)
Пример #42
0
def create_translation(client_id, contents=list(), gist_type='Service'):
    gist = TranslationGist(client_id=client_id, type=gist_type)
    DBSession.add(gist)
    DBSession.flush()
    for content in contents:
        atom = TranslationAtom(client_id=client_id,
                               content=content[0],
                               locale_id=content[1],
                               parent=gist)
        DBSession.add(atom)
    DBSession.flush()
    return gist
Пример #43
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        admin = Admin(name='admin', pw='admin')
        DBSession.add(admin)
Пример #44
0
def init_test_db():
    """Create testing database."""
    engine = create_engine("sqlite://")
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)
    with transaction.manager:
        model = Record(timestamp=datetime.utcnow(),
                       bp_upper=120,
                       bp_lower=70,
                       notes="")
        DBSession.add(model)  # pylint: disable=E1101
    return DBSession
Пример #45
0
def create_config(env):
    from intranet3.models import *
    import transaction
    config = ApplicationConfig(
        office_ip='',
        google_user_email='',
        google_user_password='',
        holidays_spreadsheet='',
        hours_employee_project='',
    )
    DBSession.add(config)
    transaction.commit()
Пример #46
0
def main(argv=sys.argv):
    print 'called'
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = Users(first_name='Julien', last_name='waddle')
        DBSession.add(model)
Пример #47
0
    def add(cls, name, url):
        ret = True
        session = DBSession()
        record = Action(name, url)
        session.add(record)
        try:
            session.commit()
            session.close()
            logging.info('add action success<name=%s, url=%s>' % (name, url))
        except IntegrityError as error:
            logging.error(str(error))
            ret = False

        return ret
Пример #48
0
 def on_remove_admin_user(cls, company_id):
     """ 删除公司管理员用户 """
     session = DBSession()
     com = session.query(cls).filter(cls.company_id == company_id).first()
     if com:
         com.admin_user_id = None
         try:
             session.add(com)
             session.commit()
         except Exception as why:
             message = "companies.on_remove_admin_user: {0}".format(why)
             logging.info(message)
             return -1
     return 0
Пример #49
0
 def add_servers(self):
     data = self.request.json
     with transaction.manager:
         server = Server(**data)
         DBSession.add(server)
         DBSession.flush()
         qs = DBSession.query(Server)
         qs.session.refresh(server)
         return {
             'uid': server.uid,
             'address': server.address,
             'port': server.port,
             'useSSL': server.useSSL
         }
Пример #50
0
def make_session(user, sessionid=None, expires_in=3600):
    if not sessionid:
        sessionid = str(uuid.uuid4())
    DBSession.query(Session).filter(Session.sessionid == sessionid).delete()
    logging.debug("making session for %s with sessionid %s" %
                  (user.username, sessionid))
    s = Session(user_id=user.id,
                sessionid=sessionid,
                expires=datetime.datetime.now() +
                datetime.timedelta(0, expires_in))
    DBSession.add(s)
    DBSession.flush()
    DBSession.expunge(s)
    return s
Пример #51
0
    def emit(self, record):
        trace = None
        exc = record.__dict__['exc_info']
        if exc:
            trace = traceback.format_exc()
        log = Log(
            logger=record.__dict__['name'],
            level=record.__dict__['levelname'],
            trace=trace,
            msg=record.__dict__['msg'],)
        #print(log.__dict__)

        DBSession.add(log)
        transaction.commit()
Пример #52
0
def create_note(request):
    user = get_current_user(request)
    form = Form(
        request, schema=NoteSchema(), state=State(user=user))
    if form.validate():
        note = form.bind(Note())
        note.user = user
        DBSession.add(note)
        request.session.flash(u'Note is successfully created', 'success')
        return HTTPFound(location=request.route_url('notes'))
    return _response_dict(
        request,
        renderer=FormRenderer(form)
    )
Пример #53
0
def settings(request):
    user = get_current_user(request)
    form = Form(
        request, ChangePasswordSchema(),
        state=State(user=user)
    )
    if form.validate():
        user.password = form.data['password']
        DBSession.add(user)

        request.session.flash(u'Password was successfully changed', 'success')
        return HTTPFound(location=request.route_url('settings'))
    return _response_dict(
        request, renderer=FormRenderer(form)
    )
Пример #54
0
 def vote_article(self, artId):
     data = {
         "userId": self.userId,
         "accessToken": self.accessToken,
         "artId": artId
     }
     r = requests.post(VOTE_ARTICLE_API, data, verify=False)
     result = r.json()
     vote = VoteRecord(artId=artId,
                       result=result['res'],
                       message=result['resMsg'])
     session = DBSession()
     session.add(vote)
     session.commit()
     session.close()
Пример #55
0
 def on_set_admin_user(cls, company_id, user_id):
     """ 设置公司管理用户 """
     session = DBSession()
     com = session.query(cls).filter(cls.company_id == company_id).first()
     if com:
         com.admin_user_id = user_id
         try:
             session.add(com)
             session.commit()
         except Exception as why:
             session.rollback()
             message = "companies.on_set_admin_user: {0}".format(why)
             logging.info(message)
             return -1
     return 0