Esempio n. 1
0
def login():

    html_content = session.get(login_url, headers=headers).content
    soup = BeautifulSoup(html_content, 'html.parser', from_encoding='utf-8')
    captcha_node = soup.find('img', id='captcha_image')
    if captcha_node is not None:
        img_url = captcha_node['src']
        image = requests.get(img_url)
        path = "tmp_file\captcha.jpg"
        #try:
        with open(path, 'wb') as f:
            for chunk in image:
                f.write(chunk)
        Image.open(path).show()
        params['captcha-solution'] = input("请输入图片中的验证码:\n")
        params['captcha-id'] = soup.select(
            'input[name="captcha-id"]')[0]["value"]
        params['source'] = "book"
        params['redir'] = "https://book.douban.com/"
        params['login'] = "******"
        #except:b
        #    print("读取验证码失败,请稍后再试")
    post_content = session.post(login_url, params=params, headers=headers)
    s = session.get(setting_url)
    return s.status_code
Esempio n. 2
0
 def test_session_request(self):
     for driver in ('memory', 'cookie'):
         session = self.app.make('SessionManager').driver(driver)
         session.set('username', 'pep')
         session.set('password', 'secret')
         assert session.get('username') == 'pep'
         assert session.get('password') == 'secret'
Esempio n. 3
0
 def test_session_flash_data_serializes_dict(self):
     for driver in ('cookie', 'memory'):
         session = self.app.make('SessionManager').driver(driver)
         session._session = {}
         session.flash('flash_dict', {'id': 1})
         session.set('get_dict', {'id': 1})
         assert session.get('flash_dict') == {'id': 1}
         assert session.get('get_dict') == {'id': 1}
Esempio n. 4
0
 def test_session_flash_data(self):
     for driver in ('memory', 'cookie'):
         session = self.app.make('SessionManager').driver(driver)
         session._session = {}
         session.flash('flash_username', 'pep')
         session.flash('flash_password', 'secret')
         assert session.get('flash_username') == 'pep'
         assert session.get('flash_password') == 'secret'
Esempio n. 5
0
def list_video(cid):
    """
    列出某个专栏下的所有课程视频
    :param cid: 专栏id
    :return: 视频列表
    """
    video_list = []
    page = 0
    url_format = "https://h5.renrenjiang.cn/api/v2/columns/{0}/activities?u=1052944&activity_sort=ASC&page={1}"
    while True:
        page += 1
        url = url_format.format(cid, page)
        res = session.get(url, headers=head)
        res = json.loads(res.content)
        if "activities" in res.keys() and len(res["activities"]) > 0:
            activities = res["activities"]
            for activity in activities:
                activity_id = activity["id"]
                title = activity["title"]
                password = activity["password"]
                start_at = activity["started_at"]
                description = activity["creator"]["description"]
                video_list.append({
                    "id": activity_id,
                    "title": title,
                    "password": password,
                    "start_at": start_at,
                    "description": description
                })
        else:
            break
    return video_list
Esempio n. 6
0
def showRecordDetail(id):
    if request.method == 'GET':

        admin = session.get('admin')
        username = request.args.get('username')

        record = Record.query.filter_by(id=id).first()

        id = record.id
        lines = record.pathline
        start = record.startpoint
        end = record.endpoint

        Longitudes = []
        Latitudes = []

        pointsStr = lines.split(';')
        result = ''

        for pointStr in pointsStr:
            point = pointStr.split(',')
            result = result + '[' + point[1] + ',' + point[0] + '],'

        result = result[:-1]  #去掉最后一个 逗号

        return render_template('recordDetail.html',
                               admin=admin,
                               username=username,
                               points=result)
Esempio n. 7
0
    def call_metapost_all_glyphs(self, master):
        writeGlobalParam(self.get_project())

        hasglyphs = False
        for glyph in master.get_glyphs():
            _glyphs = models.Glyph.filter(name=glyph.name)
            _glyphs = _glyphs.filter(models.Glyph.master_id.in_(map(lambda x: x.id, self._masters)))

            glyphs = []
            for m in self._masters:
                for g in _glyphs:
                    if g.master_id == m.id:
                        glyphs.append(g)
                        break

            if session.get('mfparser', '') == 'controlpoints':
                import xmltomf_new_2axes as xmltomf
                xmltomf.xmltomf1(self.get_lft_master(), *list(glyphs))
            else:
                import xmltomf
                xmltomf.xmltomf1(self.get_lft_master(), *list(glyphs))
            hasglyphs = True

        if hasglyphs:
            writeGlyphlist(master)
            makefont_single(self.get_lft_master())
Esempio n. 8
0
def postData():
    if request.method == 'POST':
        username = request.form.get('username')
        distance = request.form.get('distance')
        duration = request.form.get('duration')
        averagespeed = request.form.get('averagespeed')
        pathline = request.form.get('pathline')
        startpoint = request.form.get('startpoint')
        endpoint = request.form.get('endpoint')
        date = request.form.get('date')

        if session.get(username):
            newRecord = Record(username, distance, duration, averagespeed,
                               pathline, startpoint, endpoint, date)
            try:
                db.session.add(newRecord)
                db.session.commit()
                db.session.close()
                print('用户 {} 添加一条记录'.format(username))
                return jsonify({'msg': '同步记录成功!', 'state': 'success'})
            except:
                db.session.rollback()
                return jsonify({'msg': 'sql 执行错误!', 'state': 'fail'})
        else:
            return jsonify({'msg': '用户未登录!', 'state': 'fail'})
Esempio n. 9
0
def makefont_single(master, cell=''):
    if not project_exists(master):
        return False

    cell = cell.upper()
    os.environ['MFINPUTS'] = master.get_fonts_directory()
    os.environ['MFMODE'] = session.get('mfparser', '')
    if cell == 'A':
        metafont = master.get_metafont('a')
    else:
        metafont = master.get_metafont()

    import subprocess
    process = subprocess.Popen(
        ["sh", "makefont.sh", metafont],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=working_dir()
    )

    while True:
        line = process.stdout.readline()
        if not line or '<to be read again>' in line:
            process.kill()
            break
Esempio n. 10
0
def get_m3u8_by_pay(vid):
    url = "https://api.renrenjiang.cn/api/v3/activities/{0}/stream_url?user_id={1}&timestamp={2}"
    url = url.format(vid, user_id, current_milli_time())
    res = session.get(url, headers=head)
    res = json.loads(res.content)
    if "status" in res.keys() and res["status"] == 2:
        hls_url = res["hls_url"]
        return hls_url
    return None
Esempio n. 11
0
def add_card():
    """Add card to database."""
    if request.method == 'POST':
        data = request.form.to_dict()
        if user_loggined():
            uid = session.get('user_id')
            cnb1 = data.get('cnb1')
            cnb2 = data.get('cnb2')
            cnb3 = data.get('cnb3')
            cnb4 = data.get('cnb4')
            c_type = data.get('type')
            vval = data.get('vval')
            month = data.get('month')
            year = data.get('year')

            if c_type in ['visa', 'master'] and \
                    check_int(cnb1, 4) and      \
                    check_int(cnb2, 4) and      \
                    check_int(cnb3, 4) and      \
                    check_int(cnb4, 4) and      \
                    check_int(vval, 3) and      \
                    check_int(month, 2) and     \
                    check_int(year, 2):
                card = models.Card(type=c_type,
                                   cnb=' '.join([cnb1, cnb2, cnb3, cnb4]),
                                   month=month,
                                   year='20' + year,
                                   vval=vval,
                                   user_id=uid)
                db.session.add(card)
                db.session.commit()
            else:
                session['error'] = {}
                session['error']['card'] = True
                if c_type not in ['visa', 'master']:
                    session['error_msg'] = 'Unknown card type.'
                elif not (check_int(cnb1, 4) and check_int(cnb2, 4)
                          and check_int(cnb3, 4) and check_int(cnb4, 4)):
                    session['error_msg'] = 'Invalid card number.'
                elif not check_int(month, 2):
                    session['error_msg'] = 'Invalid expiry month.'
                elif not check_int(year, 2):
                    session['error_msg'] = 'Invalid expiry year.'
                else:
                    session['error_msg'] = 'Something went wrong.'
                return redirect(url_for('index') + '#card')

    return redirect(url_for('index') + '#order')
Esempio n. 12
0
def add_address():
    """Add address to database."""
    if request.method == 'POST':
        data = request.form.to_dict()
        if user_loggined():
            uid = session.get('user_id')
            country = data.get('country')
            address = data.get('address')
            city = data.get('city')
            zip_ = data.get('zip')
            if country is not None and              \
                    country in KNOWN_COUNTRIES and  \
                    city is not None and            \
                    address is not None and         \
                    len(address) < 30 and           \
                    len(city) < 15 and              \
                    check_int(zip_, 6):
                adr = models.Address(country=country,
                                     city=city,
                                     address=address,
                                     zip=zip_,
                                     user_id=uid)
                db.session.add(adr)
                db.session.commit()
            else:
                session['error'] = {}
                session['error']['address'] = True
                if country is None:
                    session['error_msg'] = 'Country is not specified.'
                elif country not in KNOWN_COUNTRIES:
                    session['error_msg'] = 'Unknown country.'
                elif city is None:
                    session['error_msg'] = 'City is not specified.'
                elif address is None:
                    session['error_msg'] = 'Address is not specified.'
                elif not check_int(zip_, 6):
                    session['error_msg'] = 'Zip must be a six digit number.'
                elif len(address) >= 30:
                    error = 'Address must be less than 30 characters length.'
                    session['error_msg'] = error
                elif len(city) >= 15:
                    error = 'City must be less than 15 characters length.'
                    session['error_msg'] = error
                else:
                    session['error_msg'] = 'Something went wrong.'
                return redirect(url_for('index') + '#address')
    return redirect(url_for('index') + '#card')
Esempio n. 13
0
    def get_glyphs_jsondata(self, glyphid, master):
        self.call_metapost(glyphid)

        project = self.get_project()

        instancelog = project.get_instancelog(self.get_lft_version())
        M_glyphjson = get_edges_json(instancelog, glyphid)

        glyph = models.Glyph.get(master_id=master.id, name=glyphid)
        instancelog = project.get_instancelog(master.version, 'a')
        if session.get('mfparser', '') == 'controlpoints':
            import xmltomf_new_2axes as xmltomf
            xmltomf.xmltomf1(master, glyph)
        else:
            import xmltomf
            xmltomf.xmltomf1(master, glyph)

        writeGlyphlist(master, glyph.name)
        makefont_single(master, cell='A')

        zpoints = get_edges_json_from_db(master, glyphid)

        glyphjson = get_edges_json(instancelog, glyphid)
        return {'M': M_glyphjson, 'R': glyphjson, 'zpoints': zpoints}
Esempio n. 14
0
 def test_reset_flash_session_memory(self):
     session = self.app.make('SessionManager').driver('memory')
     session.flash('flash_', 'test_pep')
     session.reset(flash_only=True)
     self.assertIsNone(session.get('flash_'))
Esempio n. 15
0
 def test_session_flash_data_serializes_list(self):
     for driver in ('cookie', 'memory'):
         session = self.app.make('SessionManager').driver(driver)
         session._session = {}
         session.flash('flash_dict', [1, 2, 3])
         self.assertEqual(session.get('flash_dict'), [1, 2, 3])
Esempio n. 16
0
def showRecordList(username):
    if request.method == 'GET':
        admin = session.get('admin')
        return render_template('recordList.html',
                               admin=admin,
                               username=username)
Esempio n. 17
0
    def POST(self):
        postdata = web.input(masters='', project_id=0, glyphname='')

        project = models.Project.get(id=postdata.project_id)
        if not project:
            raise web.notfound()

        # we should unify masters list in case if some masters absence
        # and raise error if unavailable
        _masters = unifylist(postdata.masters.split(','))

        # masters are passed here as ordered array of masters ids as they
        # placed on editor page
        instances = models.Master.all().filter(
            models.Master.id.in_(postdata.masters.split(',')))

        masters = []
        for p in _masters:
            for m in instances:
                if m.id == int(p):
                    masters.append(m)
                    break

        self.set_masters(masters)

        version = models.Master.max(models.Master.version,
                                    project_id=project.id)

        master = models.Master.create(project_id=project.id,
                                      version=(version + 1))
        prepare_master_environment(master)

        self.initialize(project.projectname, masters[0].version,
                        masters[1].version)

        self.call_metapost_all_glyphs(self.get_lft_master())

        logpath = project.get_instancelog(version=self.get_lft_master().version)
        for glyph in self.get_lft_master().get_glyphs():
            json = get_edges_json(logpath, glyph.name)
            if not json['edges']:
                raise web.badrequest(simplejson.dumps({'error': 'could not find any contours for instance in %s' % logpath}))

            zpoints = glyph.get_zpoints()

            points = []
            for i, contourpoints in enumerate(json['edges'][0]['contours']):
                if not contourpoints:
                    raise web.badrequest(simplejson.dumps({'error': 'could not find any points in contour for instance in %s' % logpath}))
                metapost_points = []
                for point in contourpoints:
                    if session.get('mfparser', '') == 'controlpoints':
                        metapost_points.append({'x': self.round(point['controls'][0]['x']),
                                                'y': self.round(point['controls'][0]['y'])})

                    metapost_points.append({'x': self.round(point['x']),
                                            'y': self.round(point['y'])})

                    if session.get('mfparser', '') == 'controlpoints':
                        metapost_points.append({'x': self.round(point['controls'][1]['x']),
                                                'y': self.round(point['controls'][1]['y'])})
                if session.get('mfparser', '') == 'controlpoints' and metapost_points:
                    if i != 0:
                        points_ = metapost_points[1:] + metapost_points[:1]
                        points += points_
                    else:
                        points_ = metapost_points[2:] + metapost_points[:2]
                        points += points_[::-1]
                else:
                    points += metapost_points

            if len(zpoints) != len(points):
                raise web.badrequest(simplejson.dumps({'error': '%s zp != mp %s' % (len(zpoints), len(points))}))

            newglypha = models.Glyph.create(master_id=master.id,
                                            name=glyph.name,
                                            width=glyph.width,
                                            project_id=glyph.project_id)

            i = 0
            for point in points:
                self.create_glyphpoint(newglypha, (i + 1), zpoints[i], point)
                i += 1

        project.masters = ','.join([str(master.id)] * len(project.masters.split(',')))

        glyph = models.Glyph.get(name=postdata.glyphname, master_id=master.id)
        result = self.get_glyphs_jsondata(glyph.name, master)
        return simplejson.dumps({'version': '{0:03d}'.format(master.version),
                                 'master_id': master.id, 'glyphdata': result,
                                 'versions': get_versions(master.project_id)})
Esempio n. 18
0
def ls(message, session):
    count = session.get("ls", 0) + 1
    return u"""历史推送 第%d页""" % (count,)
Esempio n. 19
0
 def test_reset_session(self):
     for driver in ('memory', 'cookie'):
         session = self.app.make('SessionManager').driver(driver)
         session.set('flash_', 'test_pep')
         session.reset()
         assert session.get('reset_username') is None
Esempio n. 20
0
def add_order():
    """Add order to data base."""
    if request.method == 'POST':
        type_ = None
        country = None
        zip_ = None
        city = None
        address = None
        vval = None
        year = None
        month = None
        cnb = None
        data = request.form.to_dict()
        if user_loggined():
            uid = session.get('user_id')
            user = models.User.query.get(uid)
            name = data.get('name')
            email = data.get('email')

            card = data.get('card')
            u_cards = user.cards.all()
            for _card in u_cards:
                if _card.type[:4] == card[:4] and _card.cnb[-9:] == card[-9:]:
                    type_ = _card.type
                    cnb = _card.cnb
                    month = _card.month
                    year = _card.year
                    vval = _card.vval

            adr = data.get('adr')
            u_addresses = user.addresses.all()
            for _adr in u_addresses:
                if adr == _adr.address:
                    address = _adr.address
                    city = _adr.city
                    zip_ = _adr.zip
                    country = _adr.country
            clothes_name = data.get('clothes_name')
            clothes_colors = data.get('clothes_colors')
            size = data.get('size')
            tel = data.get('tel')
            if name is not None and                 \
                    email is not None and           \
                    type_ is not None and           \
                    cnb is not None and             \
                    month is not None and           \
                    year is not None and            \
                    vval is not None and            \
                    address is not None and         \
                    city is not None and            \
                    zip_ is not None and            \
                    country is not None and         \
                    clothes_name is not None and    \
                    clothes_colors is not None and  \
                    size is not None and            \
                    tel is not None:

                _max = 1
                for _order in models.Order.query.all():
                    _max = max(_max, _order.order_id)
                colors = pickle.dumps(clothes_colors.split(' '))
                order = models.Order(order_id=_max + 1,
                                     user_id=uid,
                                     name=name,
                                     email=email,
                                     clothes_name=clothes_name,
                                     size=size,
                                     tel=tel,
                                     card=card,
                                     adr=adr,
                                     clothes_colors=colors)
                db.session.add(order)
                db.session.commit()
    return redirect(url_for('index'))
Esempio n. 21
0
 def test_change_ip_address(self):
     for driver in ('memory', 'cookie'):
         session = self.app.make('SessionManager').driver(driver)
         session.environ['REMOTE_ADDR'] = '111.222.33.44'
         session.set('username', 'pep')
         assert session.get('username') == 'pep'
 def download_book_html(self, bookurl):
     full_url = urllib.parse.urljoin("https://book.douban.com/subject/",
                                     bookurl)
     response = session.get(full_url)
     return response.content
Esempio n. 23
0
    def test_reset_flash_session_driver(self):
        session = self.app.make('SessionManager').driver('cookie')
        session.flash('flash_', 'test_pep')

        session.reset(flash_only=True)
        assert session.get('flash_') is None
Esempio n. 24
0
def showMain():
    admin = session.get('admin')
    return render_template('main.html', admin=admin)