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


Python Session.close方法代码示例

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


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

示例1: buildUrl

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def buildUrl():
    "生成短网址"
    
    url = request.form.get("url",None)
    token=hashlib.md5(url).hexdigest()
    
    dbSession=Session()
    query=dbSession.query(UrlModel)
    obj=query.filter(UrlModel.token == token).first()
    
    if obj == None:
        obj = UrlModel(token,url)
        dbSession.add(obj)
        dbSession.commit()
        key = obj.id 
    else:
        key = obj.id    
    dbSession.close()
    
    key=str(hex(key))[2:]
    key=key[:len(key)-1]
    key="http://"+request.headers['host']+"/shortUrl/s/"+key
    
    response = make_response(json.dumps({"key":key}))
    response.headers['Content-Type']="application/json"
    return response
开发者ID:wangjun,项目名称:shortUrl-1,代码行数:28,代码来源:app.py

示例2: update_volume_with_email_passwd

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def update_volume_with_email_passwd(models, email=None, passwd=None):
    session = Session()
    #kwdict = getvolume(models, email, passwd)
    if not hasattr(update_volume_with_email_passwd, 'ks'):
        setattr(update_volume_with_email_passwd, 'ks', KeywordSearch())
    ks = update_volume_with_email_passwd.ks
    kwdict = ks.search(models)

    for k, v in kwdict.items():
        print k, v
        m = session.query(Model).filter_by(model=k).first()
        if m:
            m.global_volume = volume2int(v[0])
            m.local_volume = volume2int(v[1])
            m.updated_at = datetime.utcnow()
            session.add(m)

    session.commit()
    session.close()
    sleep = 3
    while sleep>0:
        import time
        print 'sleeping', sleep
        time.sleep(1)
        sleep -= 1
开发者ID:mobishift2011,项目名称:amzn,代码行数:27,代码来源:volume.py

示例3: get_friends

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def get_friends(username=None):

	session = Session()
	session.expire_on_commit = False

	fan = session.query(FacebookUser).filter(FacebookUser.username==username).first()

	print "Friends of %s" % fan.username

	fan.data = "in progress"
	session.commit()

	for result in scraper.get_friends_nograph(fan.username):
		print result
		current_user = save_user(result, session, log=False)
		fan.friend(current_user)
		print "\t-", fan.username, "is friends with", current_user.username
		session.commit()

	fan.data = "done"
	fan_friends_count = fan.friends.count()

	session.commit()
	session.close()

	return "downloaded %d friends for %s" % (fan_friends_count, fan.username)
开发者ID:CK3thou,项目名称:nusocialgraph,代码行数:28,代码来源:get_friends.py

示例4: register

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def register():
    if 'username' not in request.form or 'filename' not in request.form or 'hash' not in request.form or 'size' not in request.form:
        return "\"POST request must contain 'username', 'filename', 'size', and 'hash'.\""
    session = Session()
    username = request.form['username']
    filename = request.form['filename']
    md5 = request.form['hash']
    size = request.form['size']
    files = session.query(File).filter(File.filename == filename).filter(File.md5 == md5)
    files = files.all()
    if len(files) == 0:
        f = File(filename= filename, md5 = md5, filesize = size)
        session.add(f)
        session.commit()
    else:
        f = files[0]
    fileid = f.id
    if 'path' in request.form:
        loc = request.form['path']
    else:
        loc = filename

    print username, filename, md5, loc
    if not session.query(Owner).filter(Owner.owner == username).filter(Owner.dirpath == loc).filter(Owner.fileid == fileid).all():
        session.add(Owner(owner = username, dirpath = loc, fileid = fileid))
    session.commit()
    session.close()
    return json.dumps(True)
开发者ID:ndm25,项目名称:sp2p,代码行数:30,代码来源:privclient.py

示例5: signin

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def signin():
    if 'username' not in request.form or 'secret' not in request.form or 'openport' not in request.form:
        return "\"POST request must contain 'openport', 'username' and 'secret' fields\""
    session = Session()
    username = request.form['username']
    secret = request.form['secret']
    openport = int(request.form['openport'])
    users = session.query(User).filter(User.id == username).all()
    if (len(users) == 0):
        now = datetime.datetime.now()
        user = User(id=username, secret = secret, lastping = now, lastip=request.remote_addr, lastport = openport)
        session.add(user)
        session.commit()
        session.close()
        return json.dumps("True")
    else:
        if users[0].secret == secret:
            users[0].lastip = request.remote_addr
            users[0].lastport = openport
            users[0].lastping = datetime.datetime.now()
            session.add(users[0])
            for ownership in session.query(Owner).filter(Owner.owner == username).all():
                session.delete(ownership)
            session.commit()
            session.close()
            return json.dumps(True)
        else:
            return json.dumps(False)
开发者ID:ndm25,项目名称:sp2p,代码行数:30,代码来源:privclient.py

示例6: get_by_id

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def get_by_id(img_id, width, height):
    s = Session()
    img = s.query(FlickrImage).filter(FlickrImage.id==img_id).first()
    if not img:
        abort(404)
    cropped = img.get_cropped(width, height, s)
    response = send_file(cropped.path, mimetypes.guess_type(cropped.path)[0])
    s.close()
    return response
开发者ID:jpalay,项目名称:slothr,代码行数:11,代码来源:slothr.py

示例7: main

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def main():
    success = 0

    try:
        args = parse_arguments()
    except ArgumentError as e:
        return e

    try:
        fetch_environment_variables(args)
    except ArgumentError as e:
        return e

    session = Session()

    status = False

    if args.report_user and args.report_pass:
        auth = (args.report_user, args.report_pass)
    else:
        auth = ()

    try:
        if args.command == 'scanall':
            status = scanall(
                args.ss_url, session,
                report_url=args.report_url, report_auth=auth,
                throttle_time=args.throttle
            )
        elif args.command == 'scan':
            session_id = str(uuid4())
            status = scan(
                args.aip, args.ss_url, session,
                report_url=args.report_url, report_auth=auth,
                session_id=session_id
            )
        else:
            return Exception('Error: "{}" is not a valid command.'.format(args.command))

        session.commit()
    except Exception as e:
        session.rollback()
        if args.debug:
            traceback.print_exc()
        return e
    finally:
        session.close()

    if status is True:
        success = 0
    elif status is False:
        success = 1
    else:
        success = status

    return success
开发者ID:VonRosenchild,项目名称:fixity,代码行数:58,代码来源:fixity.py

示例8: __init__

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
 def __init__(self, request):
     self.page = request.GET.get('page', '1')
     from paginate import Page
     dbsession = Session()
     articles = dbsession.query(Articles).all()
     self.paged_articles = Page(
         articles,
         page=self.page,
         items_per_page=8,
     )
     dbsession.close()
开发者ID:IYism,项目名称:lectures.www,代码行数:13,代码来源:views.py

示例9: update_volume

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def update_volume():
    blocksize = 50
    concurrency = 1 #len(CREDENTIALS)
    
    count = 0
    while True:
        count += 1
        print 'looping...', count
        session = Session()
        OFFSET = random.randint(100, 10000)
        models = (m.model.lower() for m in session.query(Model).filter(Model.global_volume == None).offset(OFFSET).limit(blocksize*concurrency))
        if not models:
            break

        models = [ normalizemodel(m) for m in models ]

        update_volume_with_email_passwd(models)

        session.close()
开发者ID:mobishift2011,项目名称:amzn,代码行数:21,代码来源:volume.py

示例10: response

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
 def response(self):
     if self.request.method == 'POST':
         submitted = self.request.POST.items()
         try:
             self.get_form().validate(submitted)
         except deform.ValidationFailure as e:
             return Response(
                 env.get_template('create.html').render(form=e.render()))
         article = Articles(**{'title': self.request.POST['title'],
                               'content': self.request.POST['content']
                               })
         dbsession = Session()
         dbsession.add(article)
         dbsession.commit()
         dbsession.close()
         self.session = get_session(self.request).pop('csrf')
         return Response(status=302, location='/blog/')
     return Response(env.get_template('create.html')
                     .render(form=self.get_form().render()))
开发者ID:IYism,项目名称:lectures.www,代码行数:21,代码来源:views.py

示例11: get_image

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def get_image(width, height):
    s = Session()
    ratio = float(width) / height
    imgs = []
    for img in s.query(FlickrImage).all():
        imgs.append({
            'ratio_diff': abs((float(img.width) / img.height) - ratio),
            'img': img
        })
    imgs = sorted(imgs, key=lambda d: d['ratio_diff'])
    # Choose a random image to spice things up a bit ;)
    img = imgs[randrange(4)]['img']
    cropped = img.get_cropped(width, height, s)
    response = send_file(cropped.path, mimetypes.guess_type(cropped.path)[0])
    s.close()
    response.headers.add('Last-Modified', datetime.datetime.now())
    response.headers.add('Cache-Control', 
            'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
    response.headers.add('Pragma', 'no-cache')
    return response
开发者ID:jpalay,项目名称:slothr,代码行数:22,代码来源:slothr.py

示例12: s

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
def s(key):
    "转到指定网址"
    key=int("0x"+key,16)
    
    global cache
    cacheKey="shortUrl_"+str(key)
    r=cache.get(cacheKey)
    
    if r == None:
        dbSession=Session()
        obj=dbSession.query(UrlModel).filter(UrlModel.id == key).first()
    
        if obj == None:
            r = None
        else:
            r = obj.url
            cache.set(cacheKey,r)
        dbSession.close()
    
    if r == None:
        return abort(404)
    
    return redirect(r)
开发者ID:wangjun,项目名称:shortUrl-1,代码行数:25,代码来源:app.py

示例13: __init__

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
class Seeder:
    """
    Seeder
    """

    def __init__(self, number_of_cities=60, number_of_travels=30):
        """
        Constructor
        :param session: Session
        :param number_of_cities: integer
        :param number_of_travels: integer
        :return: void
        """
        self.session = Session()
        self.travel_service = TravelService()
        self.city_service = CityService()
        self.fake = Factory.create()
        self.number_of_cities = number_of_cities
        self.number_of_travels = number_of_travels

    def run(self):
        """
        Point d'entrée
        :return: void
        """
        self.seed_cities(self.number_of_cities)
        self.seed_travels(self.number_of_travels)
        self.session.close()

    def seed_cities(self, number):
        """
        Crée des enregistrements aléatoires dans la table des villes
        :param number: nombre de villes
        :return: void
        """
        for i in range(0, number):
            city = City()
            city.name = self.fake.city()
            city.country = self.fake.country()
            city.is_capital = self.fake.pybool()
            self.city_service.save(city)

        capitals = self.city_service.all_capitals()
        non_capitals = self.city_service.all_non_capitals()

        for city in non_capitals:
            city.capital_id = random.choice(capitals).id
            self.city_service.save(city)

    def seed_travels(self, number):
        """
        Crée des enregistrements aléatoires dans la table des voyages
        :param number: nombre de voyages
        :return: void
        """
        cities = self.city_service.all()

        for i in range(0, number):
            travel = Travel()
            travel.start = self.fake.date_time_this_year(before_now=True, after_now=False)
            travel.end = travel.start + datetime.timedelta(days=random.randrange(1, 10, 1))
            travel.review = self.fake.text(max_nb_chars=200)
            travel.city_id = random.choice(cities).id

            for j in range(0, 3):
                transport = Transport()
                transport.type = random.choice(['Train', 'Avion', 'Voiture', 'Bateau', 'Bus'])
                transport.price = random.randrange(10, 150, 5)
                transport.duration = random.randrange(1, 24, 1)
                travel.transports.append(transport)

            for k in range(0, 3):
                accomodation = Accomodation()
                accomodation.name = self.fake.company()
                accomodation.type = random.choice(['Camping', 'Hôtel', 'Gîte', 'Appartement'])
                accomodation.price = random.randrange(50, 500, 10)
                travel.accomodations.append(accomodation)

            self.travel_service.save(travel)
开发者ID:MarvinDurot,项目名称:travel_manager,代码行数:81,代码来源:seeder.py

示例14: print

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
import os
import sys
import json

from dotenv import load_dotenv, find_dotenv
from slackclient import SlackClient

from models import EmojiList, Session

current_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(current_dir)
print(current_dir)

load_dotenv(find_dotenv())
token = os.environ['SLACK_API_TOKEN']
slack = SlackClient(token)
res = slack.api_call('emoji.list')
if res['ok'] == False:
    print('API Fail')
    sys.exit(1)

session = Session()
data = json.dumps(res['emoji'])
el = EmojiList(data=data)
session.add(el)
session.commit()
print(el.id)
session.close()
开发者ID:yamada-h,项目名称:dotfiles,代码行数:30,代码来源:check.py

示例15: __init__

# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import close [as 别名]
class GenericService:
    """
    Service générique permettant de manipuler
    les modèles en base plus simplement.
    """
    __modelClass__ = None

    def __init__(self):
        """
        Constructeur
        :return:
        """
        self.session = None

    def newSession(self):
        """
        Renouvelle la session du service
        :return:
        """
        if self.session is not None:
            self.session.close()
        else:
            self.session = Session()

    def all(self):
        """
        Récupère tous les enregitrements
        :return: list
        """
        self.newSession()
        return self.session.query(self.__modelClass__).all()

    def find(self, id):
        """
        Récupère un enregistrement
        :param id: id de l'enregistrement
        :return: object
        """
        self.newSession()
        return self.session.query(self.__modelClass__).get(id)

    def delete(self, id):
        """
        Supprime un enregistrement en base
        :param id: id de l'enregistrement
        :return: void
        """
        self.newSession()
        obj = self.session.query(self.__modelClass__).get(id)
        self.session.delete(obj)
        self.session.commit()
        self.session.flush()

    def save(self, obj):
        """
        Crée ou met à jour un enregistrement en base
        :param obj: l'objet à sauvegarder
        :return: void
        """
        self.newSession()
        self.session.add(obj)
        self.session.commit()
        self.session.flush()

    def __del__(self):
        """
        Ferme la session à la destruction de la classe
        :return:
        """
        self.session.close()
开发者ID:MarvinDurot,项目名称:travel_manager,代码行数:72,代码来源:services.py


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