Пример #1
0
def get_participant(event, nfc_id):
        try:
            participant = Participant.query.filter_by(event_id=event, nfc_id=nfc_id).first()
            response = jsonp(id=participant.id,name=participant.name, email=participant.email,twitter=participant.twitter,nfc_id=participant.nfc_id)
        except:
            response = jsonp(error="invalid")
        return response
Пример #2
0
    def test_jsonp(self):
        with self.app.test_request_context('/?callback=callback'):
            kwargs = {'lang': 'en-us', 'query': 'python'}
            r = jsonp(**kwargs)
            response = (
                u'callback({\n  "%s": "%s",\n  "%s": "%s"\n});' % (
                    'lang', kwargs['lang'], 'query', kwargs['query'])
                ).encode('utf-8')

            self.assertEqual(response, r.get_data())

        with self.app.test_request_context('/'):
            param1, param2 = 1, 2
            r = jsonp(param1=param1, param2=param2)
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
            r = jsonp({'param1': param1, 'param2': param2})
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
            r = jsonp([('param1', param1), ('param2', param2)])
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
Пример #3
0
def get_participant(nfc_id):
        try:
            participant = Participant.query.filter_by(nfc_id=nfc_id).first()
            response = jsonp(name=participant.name, email=participant.email)
        except:
            response = jsonp(error="invalid")
        return response
Пример #4
0
def jsoncomment(profile, workspace, proposal, kwargs):
    cid = kwargs['cid']
    comment = commentease.Comment.query.get(cid)
    if comment:
        return jsonp(message=comment.message)
    else:
        return jsonp(message='')
Пример #5
0
def jsoncomment(profile, project, event, comment):
    if not event:
        abort(404)
    if not project:
        abort(404)
    if not comment:
        abort(404)

    # comment = Comment.query.get(cid)
    if comment:
        return jsonp(message=comment.message)
    else:
        return jsonp(message='')
Пример #6
0
def jsoncomment(name, slug, cid):
    space = ProposalSpace.query.filter_by(name=name).first()
    if not space:
        abort(404)
    proposal_id = int(slug.split('-')[0])
    proposal = Proposal.query.get(proposal_id)
    if not proposal:
        abort(404)

    comment = Comment.query.get(cid)
    if comment:
        return jsonp(message=comment.message)
    else:
        return jsonp(message='')
Пример #7
0
def viewspace_json(name):
    space = ProposalSpace.query.filter_by(name=name).first_or_404()
    sections = ProposalSpaceSection.query.filter_by(proposal_space=space).order_by("title").all()
    proposals = Proposal.query.filter_by(proposal_space=space).order_by(db.desc("created_at")).all()
    return jsonp(
        **{
            "space": {
                "name": space.name,
                "title": space.title,
                "datelocation": space.datelocation,
                "status": space.status,
            },
            "sections": [{"name": s.name, "title": s.title, "description": s.description} for s in sections],
            "proposals": [
                {
                    "id": proposal.id,
                    "name": proposal.urlname,
                    "title": proposal.title,
                    "url": url_for("viewsession", name=space.name, slug=proposal.urlname, _external=True),
                    "proposer": proposal.user.fullname,
                    "speaker": proposal.speaker.fullname if proposal.speaker else None,
                    "email": proposal.email if lastuser.has_permission("siteadmin") else None,
                    "phone": proposal.phone if lastuser.has_permission("siteadmin") else None,
                    "section": proposal.section.title,
                    "type": proposal.session_type,
                    "level": proposal.technical_level,
                    "votes": proposal.votes.count,
                    "comments": proposal.comments.count,
                    "submitted": proposal.created_at.isoformat(),
                    "confirmed": proposal.confirmed,
                }
                for proposal in proposals
            ],
        }
    )
Пример #8
0
def viewspace_json(name):
    space = ProposalSpace.query.filter_by(name=name).first_or_404()
    sections = ProposalSpaceSection.query.filter_by(proposal_space=space).order_by('title').all()
    proposals = Proposal.query.filter_by(proposal_space=space).order_by(db.desc('created_at')).all()
    return jsonp(**{
        'space': {
            'name': space.name,
            'title': space.title,
            'datelocation': space.datelocation,
            'status': space.status,
            },
        'sections': [{'name': s.name, 'title': s.title, 'description': s.description} for s in sections],
        'proposals': [{
            'id': proposal.id,
            'name': proposal.urlname,
            'title': proposal.title,
            'url': url_for('viewsession', name=space.name, slug=proposal.urlname, _external=True),
            'proposer': proposal.user.fullname,
            'speaker': proposal.speaker.fullname if proposal.speaker else '(open)',
            'email': proposal.email if g.lastuserinfo and 'siteadmin' in g.lastuserinfo.permissions else None,
            'section': proposal.section.title,
            'type': proposal.session_type,
            'level': proposal.technical_level,
            'votes': proposal.votes.count,
            'comments': proposal.comments.count,
            'submitted': proposal.created_at.isoformat(),
            } for proposal in proposals]
        })
Пример #9
0
def nlp_extract_tags(text, lang=None):
    """
    Return a list of tags extracted from provided text.
    """

    sentences = nltk.sent_tokenize(text)
    tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
    tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
    chunked_sentences = nltk.batch_ne_chunk(tagged_sentences, binary=True)

    def extract_entity_names(t):
        entity_names = []

        if hasattr(t, "node") and t.node:
            if t.node == "NE":
                entity_names.append(" ".join([child[0] for child in t]))
            else:
                for child in t:
                    entity_names.extend(extract_entity_names(child))

        return entity_names

    entity_names = []
    for tree in chunked_sentences:
        entity_names.extend(extract_entity_names(tree))

    result = {"tags": list(set(entity_names))}

    return jsonp({"status": "ok", "result": result})
Пример #10
0
def geo_get_by_name(name, related=False, alternate_titles=False):
    if name.isdigit():
        geoname = GeoName.query.get(int(name))
    else:
        geoname = GeoName.get(name)
    return jsonp({'status': 'ok', 'result': geoname.as_dict(related=related, alternate_titles=alternate_titles)}
        if geoname else {'status': 'error', 'error': 'not_found'})
Пример #11
0
def schedule_by_name(event):
    """
    List schedules for requested event.
    """
    if event != 'droidconin/2012':
        return jsonp(status='error', error='unknown-event', description="No such event. Use profile/workspace syntax")

    # Return static data for Droidcon
    return schedule_list(profile='off7nXRQQ7-S1ZK-D_tIdQ', workspace='Mg8vrAAlSIanvE3qsZu2Dg')
Пример #12
0
def api_result(status, **params):
    status_code = 200
    if status in (200, 201):
        status_code = status
        status = "ok"
    params["status"] = status
    response = jsonp(params)
    response.status_code = status_code
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    return response
Пример #13
0
def space_view_json(profile, space):
    sections = ProposalSpaceSection.query.filter_by(proposal_space=space, public=True).order_by('title').all()
    proposals = Proposal.query.filter_by(proposal_space=space).order_by(db.desc('created_at')).all()
    return jsonp(**{
        'space': space_data(space),
        'sections': [section_data(s) for s in sections],
        'venues': [venue_data(venue) for venue in space.venues],
        'rooms': [room_data(room) for room in space.rooms],
        'proposals': [proposal_data(proposal) for proposal in proposals],
        'schedule': schedule_data(space),
        })
Пример #14
0
def api_result(status, **params):
    status_code = 200
    if status in (200, 201):
        status_code = status
        status = 'ok'
    params['status'] = status
    response = jsonp(params)
    response.status_code = status_code
    response.headers['Cache-Control'] = 'private, no-cache, no-store, max-age=0, must-revalidate'
    response.headers['Pragma'] = 'no-cache'
    return response
Пример #15
0
def resource_error(error, description=None, uri=None):
    params = {"status": "error", "error": error}
    if description:
        params["error_description"] = description
    if uri:
        params["error_uri"] = uri

    response = jsonp(params)
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.status_code = 400
    return response
Пример #16
0
def resource_error(error, description=None, uri=None):
    params = {'status': 'error', 'error': error}
    if description:
        params['error_description'] = description
    if uri:
        params['error_uri'] = uri

    response = jsonp(params)
    response.headers['Cache-Control'] = 'no-store'
    response.headers['Pragma'] = 'no-cache'
    response.status_code = 400
    return response
Пример #17
0
def geo_get_by_names(name, related=False, alternate_titles=False):
    geonames = []
    for n in name:
        if n.isdigit():
            geoname = GeoName.query.get(int(n))
        else:
            geoname = GeoName.get(n)
        if geoname:
            geonames.append(geoname)
    return jsonp({
        'status': 'ok',
        'result': [gn.as_dict(related=related, alternate_titles=alternate_titles) for gn in geonames]
        })
Пример #18
0
def space_view_json(space):
    sections = ProposalSpaceSection.query.filter_by(proposal_space=space, public=True).order_by('title').all()
    proposals = Proposal.query.filter_by(proposal_space=space).order_by(db.desc('created_at')).all()
    return jsonp(**{
        'space': {
            'name': space.name,
            'title': space.title,
            'datelocation': space.datelocation,
            'status': space.status,
            },
        'sections': [{'name': s.name, 'title': s.title, 'description': s.description} for s in sections],
        'proposals': [proposal_data(proposal) for proposal in proposals]
        })
Пример #19
0
def session_json(name, slug):
    space = ProposalSpace.query.filter_by(name=name).first()
    if not space:
        abort(404)
    try:
        proposal_id = int(slug.split('-')[0])
    except ValueError:
        abort(404)
    proposal = Proposal.query.get(proposal_id)
    if not proposal:
        abort(404)
    if proposal.proposal_space != space:
        return redirect(url_for('viewspace', name=space.name))
    if slug != proposal.urlname:
        return redirect(url_for('session_json', name=space.name, slug=proposal.urlname))
    return jsonp(proposal_data(proposal))
Пример #20
0
def viewspace_json(name):
    space = ProposalSpace.query.filter_by(name=name).first_or_404()
    sections = ProposalSpaceSection.query.filter_by(proposal_space=space).order_by("title").all()
    proposals = Proposal.query.filter_by(proposal_space=space).order_by(db.desc("created_at")).all()
    return jsonp(
        **{
            "space": {
                "name": space.name,
                "title": space.title,
                "datelocation": space.datelocation,
                "status": space.status,
            },
            "sections": [{"name": s.name, "title": s.title, "description": s.description} for s in sections],
            "proposals": [proposal_data(proposal) for proposal in proposals],
        }
    )
Пример #21
0
def events_list():
    """
    List all upcoming events.
    """
    return jsonp({
        'profiles': {
            'off7nXRQQ7-S1ZK-D_tIdQ': {
                'name': 'droidconin',
                'title': 'Droidcon India',
                'buid': 'off7nXRQQ7-S1ZK-D_tIdQ',
                },
            },
        'workspaces': {
            'Mg8vrAAlSIanvE3qsZu2Dg': {
                'profile_id': 'off7nXRQQ7-S1ZK-D_tIdQ',
                'buid': 'Mg8vrAAlSIanvE3qsZu2Dg',
                'name': '2012',
                'title': 'Droidcon India 2012',
                'short_title': '2012',
                'feature_flags': ['funnel', 'schedule'],
                'features': {
                    'artwork': {
                        'color_bg': '#ffffff',
                        'color_bg2': '#ffffff',
                        'color_fg': '#222',
                        'color_fg2': '#222',
                        'logo_url': None,
                        'cover_url': None
                        },
                    'schedule': {
                        'date_location': '2 & 3 November, Bangalore',
                        'start_date': date(2012, 11, 2).isoformat(),
                        'end_date': date(2012, 11, 3).isoformat(),
                        'start': datetime(2012, 11, 2, 3, 30, 0).isoformat() + 'Z',
                        'end': datetime(2012, 11, 3, 12, 30, 0).isoformat() + 'Z',
                        'data_api_url': url_for('schedule_list',
                            profile='off7nXRQQ7-S1ZK-D_tIdQ', workspace='Mg8vrAAlSIanvE3qsZu2Dg',
                            _external=True)
                        }
                    }
                }
            }
        })
Пример #22
0
    def test_render(self):
        """
        Test rendered views.
        """
        # For this test to pass, the render_view decorator must call render_template
        # with the correct template name. Since the templates don't actually exist,
        # we'll get a TemplateNotFound exception, so our "test" is to confirm that the
        # missing template is the one that was supposed to be rendered.
        try:
            self.app.get('/renderedview1')
        except TemplateNotFound as e:
            self.assertEqual(str(e), 'renderedview1.html')
        else:
            raise Exception("Wrong template rendered")

        for acceptheader, template in [
                ('text/html;q=0.9,text/xml;q=0.8,*/*', 'renderedview2.html'),
                ('text/xml;q=0.9,text/html;q=0.8,*/*', 'renderedview2.xml'),
                ('Text/Html,Application/Xhtml Xml,Application/Xml;Q=0.9,*/*;Q=0.8', 'renderedview2.html')]:
            try:
                self.app.get('/renderedview2', headers=[('Accept', acceptheader)])
            except TemplateNotFound as e:
                self.assertEqual(str(e), template)
            else:
                raise Exception("Wrong template rendered")

        # The application/json and text/plain renderers do exist, so we should get
        # a valid return value from them.
        response = self.app.get('/renderedview2', headers=[('Accept', 'application/json')])
        self.assertTrue(isinstance(response, Response))
        with app.test_request_context():  # jsonp requires a request context
            self.assertEqual(response.data, jsonp({"data": "value"}).data)
        response = self.app.get('/renderedview2', headers=[('Accept', 'text/plain')])
        self.assertTrue(isinstance(response, Response))
        self.assertEqual(response.data.decode('utf-8') if six.PY3 else response.data, "{'data': 'value'}")
        response = self.app.get('/renderedview3', headers=[('Accept', 'text/plain')])
        self.assertTrue(isinstance(response, Response))
        resp = self.app.get('/renderedview4', headers=[('Accept', 'text/plain')])
        self.assertEqual(resp.headers['Referrer'], "http://example.com")
Пример #23
0
def nlp_extract_tags(text, lang=None):
    '''returns list of named entities'''
    
    sample = text
    
    sentences = nltk.sent_tokenize(sample)
    tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
    tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
    chunked_sentences = nltk.batch_ne_chunk(tagged_sentences, binary=True)
     
    def extract_entity_names(t):
        entity_names = []
        
        if hasattr(t, 'node') and t.node:
            if t.node == 'NE':
                entity_names.append(' '.join([child[0] for child in t]))
            else:
                for child in t:
                    entity_names.extend(extract_entity_names(child))
                    
        return entity_names
     
    entity_names = []
    for tree in chunked_sentences:
        # Print results per sentence
        # print extract_entity_names(tree)
        
        entity_names.extend(extract_entity_names(tree))
     
    # Print all entity names
    #print entity_names
     
    # Print unique entity names
    result = {'tags': list(set(entity_names))}

    return jsonp({'status': 'ok', 'result': result})
Пример #24
0
def spaces_json(profile):
    # FIXME: Only return active spaces
    return jsonp(spaces=[space_data(space) for space in ProposalSpace.query.filter_by(profile=profile).order_by(ProposalSpace.date.desc()).all()])
Пример #25
0
def all_spaces_json():
    g.profile = None
    g.permissions = []
    # FIXME: Only return active spaces
    return jsonp(spaces=[space_data(space) for space in ProposalSpace.query.filter(ProposalSpace.profile != None).order_by(ProposalSpace.date.desc()).all()])  # NOQA
Пример #26
0
        except TemplateNotFound, e:
            self.assertEqual(str(e), 'renderedview1.html')
        else:
            raise Exception("Wrong template rendered")

        for acceptheader, template in [
                ('text/html,text/xml,*/*', 'renderedview2.html'),
                ('text/xml,text/html,*/*', 'renderedview2.xml')]:
            try:
                self.app.get('/renderedview2', headers=[('Accept', acceptheader)])
            except TemplateNotFound, e:
                self.assertEqual(str(e), template)
            else:
                raise Exception("Wrong template rendered")

        # The application/json and text/plain renderers do exist, so we should get
        # a valid return value from them.
        response = self.app.get('/renderedview2', headers=[('Accept', 'application/json')])
        self.assertTrue(isinstance(response, Response))
        with app.test_request_context():  # jsonp requires a request context
            self.assertEqual(response.data, jsonp({"data": "value"}).data)
        response = self.app.get('/renderedview2', headers=[('Accept', 'text/plain')])
        self.assertTrue(isinstance(response, Response))
        self.assertEqual(response.data, "{'data': 'value'}")
        response = self.app.get('/renderedview3', headers=[('Accept', 'text/plain')])
        self.assertTrue(isinstance(response, Response))
        resp = self.app.get('/renderedview4', headers=[('Accept', 'text/plain')])
        self.assertEqual(resp.headers['Referrer'], "http://example.com")
        #resp = self.app.get('/renderedview5', headers=[('Accept', 'text/plain')])
        #self.assertEqual(resp.status_code, 201)
Пример #27
0
def comment_json(space, proposal, comment):
    if comment:
        return jsonp(message=comment.message)
    else:
        return jsonp(message='')
Пример #28
0
def geo_parse_location(q, special=[], lang=None, bias=[]):
    result = GeoName.parse_locations(q, special, lang, bias)
    for item in result:
        if 'geoname' in item:
                item['geoname'] = item['geoname'].as_dict()
    return jsonp({'status': 'ok', 'result': result})
Пример #29
0
def api_result(status, **params):
    params['status'] = status
    response = jsonp(params)
    response.headers['Cache-Control'] = 'no-store'
    response.headers['Pragma'] = 'no-cache'
    return response
Пример #30
0
def proposal_json(profile, space, proposal):
    return jsonp(proposal_data(proposal))