当前位置: 首页>>代码示例>>Python>>正文


Python DBSession.add方法代码示例

本文整理汇总了Python中models.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.DBSession的用法示例。


在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _init

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
    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
开发者ID:P-Laf,项目名称:ofxtools,代码行数:30,代码来源:Parser.py

示例2: make_admin

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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()
开发者ID:pytlakp,项目名称:intranet-1,代码行数:30,代码来源:script.py

示例3: __init__

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
 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)
开发者ID:P-Laf,项目名称:ofxtools,代码行数:9,代码来源:Parser.py

示例4: post_entry

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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
开发者ID:aarongreenwald,项目名称:pim,代码行数:9,代码来源:views.py

示例5: instantiate

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
    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
开发者ID:P-Laf,项目名称:ofxtools,代码行数:30,代码来源:Parser.py

示例6: job_output

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
    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'])}
开发者ID:meyerjo,项目名称:ClusterJobMonitor,代码行数:30,代码来源:views.py

示例7: filemonitoring

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
    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)
开发者ID:meyerjo,项目名称:ClusterJobMonitor,代码行数:34,代码来源:fileviews.py

示例8: attach_pictures

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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)
开发者ID:tinawen,项目名称:menu,代码行数:27,代码来源:views.py

示例9: write_jobs_to_database

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
 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()
开发者ID:meyerjo,项目名称:ClusterJobMonitor,代码行数:32,代码来源:job_database_wrapper.py

示例10: postAdd

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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}
开发者ID:cs-shadow,项目名称:social-search,代码行数:36,代码来源:views.py

示例11: oauth2callback

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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!')
开发者ID:reberhardt7,项目名称:hcc-photo-upload,代码行数:29,代码来源:views.py

示例12: upload

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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')
开发者ID:reberhardt7,项目名称:hcc-photo-upload,代码行数:36,代码来源:views.py

示例13: eventAdd

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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}
开发者ID:m6394g,项目名称:pyramid,代码行数:31,代码来源:views.py

示例14: entity_type_put

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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'}
开发者ID:vishakh,项目名称:metamkt,代码行数:10,代码来源:views.py

示例15: signup

# 需要导入模块: from models import DBSession [as 别名]
# 或者: from models.DBSession import add [as 别名]
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))
开发者ID:ErwanTremiot,项目名称:notejam,代码行数:10,代码来源:views.py


注:本文中的models.DBSession.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。