コード例 #1
0
ファイル: handlers.py プロジェクト: xarg/django-snippify
def create(request):
    """ Expect a post """
    user = _auth(request)
    if user:
        data = json.loads(request.POST.get('data', '{}'))
        data['status'] = 'published'
        form = SnippetForm(data)
        if not form.is_valid():
            return HttpResponse('VALIDATION')
        try:
            lexer_obj = guess_lexer(data['body'])
            for lex in LEXERS.itervalues():
                if lexer_obj.name == lex[1]:
                    lexer = lex[2][0].lower()
                    break
        except ClassNotFound:
            lexer = u'text'
        try:
            snippet = Snippet(
                author = user,
                title = data['title'],
                description = data['description'],
                body=data['body'],
                tags=data['tags'],
                lexer=lexer,
                via=data['via'],
                privacy = data['privacy'],
                status = data['status']
            )
            snippet.save()
            return HttpResponse('SUCCESS')
        except:
            return HttpResponse('ERROR')
    else:
        return HttpResponse('NOT_AUTHORIZED')
コード例 #2
0
def snippets():
    if request.method == 'POST':
        app.logger.info(f"Adding new clock snippet to database")
        snippet = request.get_json()
        newSnippet = Snippet(filename=snippet['filename'],
                             snippet_type=snippet['snippet_type'],
                             start=snippet['start'],
                             duration=snippet['duration'])
        vid = Video.query.get(snippet['video_id'])
        newSnippet.video = vid
        db.session.add(newSnippet)
        db.session.commit()
        return jsonify(newSnippet.serialize())

    if request.args.get('video_id') and request.args.get('start'):
        start = datetime.timedelta(
            seconds=Snippet.getSec(request.args.get('start')))
        snippet = Snippet.query.filter_by(
            video_id=request.args.get('video_id'), start=start).first()
        if snippet:
            return jsonify(snippet.serialize())
        return jsonify({})

    snipz = Snippet.query.all()
    app.logger.info("Gathering list of all snippets. (Currently {len(snipz)})")
    all_snipz = []
    for snippet in snipz:
        all_snipz.append(snippet.serialize())
    return jsonify({"snippets": all_snipz})
コード例 #3
0
ファイル: views.py プロジェクト: skopp/django-cloud-ide
def save(request):
    if not request.method == 'POST' or not 'title' in request.POST:
        return HttpResponseForbidden()
    
    snippet_title = request.POST['title']
    
    if not snippet_title:
        return HttpResponseForbidden()
    
    try: # load the snippet
        snippet = Snippet.objects.get(title=snippet_title)
        if request.user.id != snippet.author.id:
            return HttpResponseForbidden()
    except Snippet.DoesNotExist: # create new snippet
        snippet = Snippet(author=request.user)
        if not title_available(snippet_title):
            return HttpResponseForbidden()
    
    response_dict = {}
    if request.is_ajax():
        form = SnippetForm(instance=snippet, data=request.POST)
        if form.is_valid():
            snippet.code = request.POST['code']
            snippet.language = Language.objects.get(name=request.POST['language'])
            snippet = form.save()
            response_dict.update({'success': True})
        else:
            response_dict.update({'errors': form.errors})
    return JsonResponse(response_dict)
コード例 #4
0
ファイル: main.py プロジェクト: moretti/python-playground
    def post(self):
        body = self.request.get('body')
        key = Snippet.create_key(body)
        snippet = key.get()
        if not snippet:
            snippet = Snippet(key=key, body=body)
            snippet.put()

        self.response.write(snippet.key.id())
コード例 #5
0
ファイル: api.py プロジェクト: flosch/django-paste
 def new(self, content, title='', author='', expires=60*60):
     
     new_snippet = Snippet(
         title=title,
         author=author,
         content=content,
         expires=datetime.datetime.now() + datetime.timedelta(seconds=expires)
     )
     new_snippet.save()
     
     return new_snippet.get_absolute_url()
コード例 #6
0
ファイル: util.py プロジェクト: marcia/snippets
def fill_in_missing_snippets(existing_snippets, user, user_email, today):
    """Make sure that the snippets array has a Snippet entry for every week.

    The db may have holes in it -- weeks where the user didn't write a
    snippet.  Augment the given snippets array so that it has no holes,
    by adding in default snippet entries if necessary.  Note it does
    not add these entries to the db, it just adds them to the array.

    Arguments:
       existing_snippets: a list of Snippet objects for a given user.
         The first snippet in the list is assumed to be the oldest
         snippet from that user (at least, it's where we start filling
         from).
       user: a User object for the person writing this snippet.
       user_email: the email of the person whose snippets it is.
       today: a datetime.datetime object representing the current day.
         We fill up to then.  If today is wed or before, then we
         fill up to the previous week.  If it's thurs or after, we
         fill up to the current week.

    Returns:
      A new list of Snippet objects, without any holes.
    """
    end_monday = newsnippet_monday(today)
    if not existing_snippets:  # no snippets at all?  Just do this week
        return [
            Snippet(email=user_email,
                    week=end_monday,
                    private=user.private_snippets,
                    is_markdown=user.uses_markdown)
        ]

    # Add a sentinel, one week past the last week we actually want.
    # We'll remove it at the end.
    existing_snippets.append(
        Snippet(email=user_email, week=end_monday + datetime.timedelta(7)))

    all_snippets = [existing_snippets[0]]  # start with the oldest snippet
    for snippet in existing_snippets[1:]:
        while snippet.week - all_snippets[-1].week > datetime.timedelta(7):
            missing_week = all_snippets[-1].week + datetime.timedelta(7)
            all_snippets.append(
                Snippet(email=user_email,
                        week=missing_week,
                        private=user.private_snippets,
                        is_markdown=user.uses_markdown))
        all_snippets.append(snippet)

    # Get rid of the sentinel we added above.
    del all_snippets[-1]

    return all_snippets
コード例 #7
0
ファイル: views.py プロジェクト: jalopez/DevWithMe
def create_snippet(request, form):
    if not form.is_valid():
        return None
    
    text = form.cleaned_data['text']
    title = form.cleaned_data['title']
    is_public = form.cleaned_data['is_public']
    
    snippet = Snippet(title=title, text=text)
    snippet.save()
    add_tags(snippet, form.cleaned_data['tags'])
    pub = Publication(content=snippet, reply_to_pub=None, is_public=is_public, published_by=request.user.get_profile())
    pub.save()
    
    return pub
コード例 #8
0
ファイル: get_snippets.py プロジェクト: andrewhead/StackSkim
def save_snippet(node, page):

    snippet = Snippet.create(
        page=page,
        text_above=extract_text_above(node),
        text_below=extract_text_below(node),
        header=extract_header_above(node),
        code=extract_code(node),
        line_count=len(node.text.split('\n')),
    )

    for tok_str in extract_tokens(node):
        token, _ = Token.get_or_create(string=tok_str)
        SnippetToken.create(
            snippet=snippet,
            token=token,
        )

    for comment_str in extract_comments(node):
        comment, _ = Comment.get_or_create(string=comment_str)
        SnippetComment.create(
            snippet=snippet,
            comment=comment,
        )

    return snippet
コード例 #9
0
    def post(self, user):
        root_args = self.parser.parse_args()
        snippet_args = self.snippetParser.parse_args(req=root_args)

        #print("New snippet:", snippet_args, snippet_args.title)
        #print("tags: ", snippet_args.tags.split(','))
        new_tag = snippet_args.tags.split(',')

        session = Session()
        snippet = Snippet(title=snippet_args.title,
                          author=snippet_args.author,
                          content=snippet_args.content,
                          tags=[Tag(name=tagName) for tagName in new_tag])
        session.add(snippet)
        session.commit()

        # this response is used by the react client to instantly construct the snippet
        return {
            'id': snippet.id,
            'title': snippet.title,
            'author': snippet.author,
            'content': snippet.content,
            #'user_id': snippet.user_id,
            'likes': snippet.likes,
            'created_at': snippet.created_at.isoformat() + 'Z',
            'tags': snippet_args.tags
            #'comments': snippet.comments
        }
コード例 #10
0
def generateReccomendations(snippets, user, numRecsToReturn):
    if numRecsToReturn > snippets.count():
        numRecToReturn = snippets.count()

    recList = []
    for index in range(0, numRecsToReturn):
        recList.append([Snippet(), 0])

    for snippet in snippets:
        userSnippetSimilarityRating = 0
        snippetTagList = snippet.tags
        for utag in user.tags:
            for ptag in snippetTagList:
                if ptag == utag:
                    userSnippetSimilarityRating += 1
                    #Don't rescan matched next iteration
                    postTagList.remove(ptag)

        # Check if this post should be included as a reccomendation, replace if neccesary
        for rec in recList:
            if rec[1] < userSnippetSimilarityRating:
                rec[0] = snippet
                rec[1] = userSnippetSimilarityRating
                break

    return recList
コード例 #11
0
    def render(self):

        for i in range(200):
            snippet = Snippet()
            snippet.headline = 'Headline ' + str(i)
            snippet.link = 'Link ' + str(i)
            snippet.copy = 'Headline ' + str(i)
            snippet.put()
コード例 #12
0
ファイル: blueprint.py プロジェクト: octt/flask
def create():
    if request.method == 'POST':
        form = SnippetForm(request.form)
        if form.validate():
            snippet = form.save_entry(Snippet())
            db.session.add(snippet)
            db.session.commit()
            return redirect(url_for('snippets.detail', slug=snippet.slug))
    else:
        form = SnippetForm()
    return render_template('snippets/create.html', form=form)
コード例 #13
0
ファイル: main.py プロジェクト: moretti/python-playground
    def get(self, snippet_id=None):
        body = 'print "Hello, playground"\n'
        if snippet_id:
            snippet = Snippet.get_by_id(snippet_id)
            if snippet:
                body = snippet.body
            else:
                self.abort(404)

        template = settings.JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render({'body': body}))
コード例 #14
0
ファイル: open_module.py プロジェクト: guardian/open-module
    def render(self):

        for i in range (200):
            snippet = Snippet()
            snippet.headline = 'Headline ' + str(i)
            snippet.link = 'Link ' + str(i)
            snippet.copy = 'Headline ' + str(i)
            snippet.put()
コード例 #15
0
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)
コード例 #16
0
ファイル: open_module.py プロジェクト: guardian/open-module
    def list(self):

        cursor = None
        bookmark = self.request.get('bookmark')
        if bookmark:
            cursor = ndb.Cursor.from_websafe_string(bookmark)

        snippets_query = Snippet.query().order(-Snippet.created)
        snippets, next_cursor, more = snippets_query.fetch_page(PAGE_SIZE, start_cursor=cursor)

        next_bookmark = None
        if more:
            next_bookmark = next_cursor.to_websafe_string()

        template = jinja_environment.get_template('list.html')
        self.response.out.write(template.render(snippets=snippets, bookmark=next_bookmark, server_url=server_url, pageName='list'))
コード例 #17
0
ファイル: open_module.py プロジェクト: guardian/open-module
    def get(self):
        id = self.request.get("id")
        snippet = Snippet.get_by_id(long(id))

        template = jinja_environment.get_template("view.html")
        html = template.render(snippet=snippet, id=id)
        jsonResponse = {
            'html' : html,
            'headline' : snippet.headline,
            'link' : snippet.link,
            'copy' : snippet.copy,
            'id' : id
        }

        self.response.headers['cache-control'] = 'max-age=900s'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.encode(jsonResponse))
コード例 #18
0
    def get(self):
        id = self.request.get("id")
        snippet = Snippet.get_by_id(long(id))

        template = jinja_environment.get_template("view.html")
        html = template.render(snippet=snippet, id=id)
        jsonResponse = {
            'html': html,
            'headline': snippet.headline,
            'link': snippet.link,
            'copy': snippet.copy,
            'id': id
        }

        self.response.headers['cache-control'] = 'max-age=900s'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.encode(jsonResponse))
コード例 #19
0
    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionary
        of deserialized field values.

        Note that if we don't define this method, then deserializing
        data will simply return a dictionary of items.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)
コード例 #20
0
    def list(self):

        cursor = None
        bookmark = self.request.get('bookmark')
        if bookmark:
            cursor = ndb.Cursor.from_websafe_string(bookmark)

        snippets_query = Snippet.query().order(-Snippet.created)
        snippets, next_cursor, more = snippets_query.fetch_page(
            PAGE_SIZE, start_cursor=cursor)

        next_bookmark = None
        if more:
            next_bookmark = next_cursor.to_websafe_string()

        template = jinja_environment.get_template('list.html')
        self.response.out.write(
            template.render(snippets=snippets,
                            bookmark=next_bookmark,
                            server_url=server_url,
                            pageName='list'))
コード例 #21
0
ファイル: app.py プロジェクト: kenmaready/funcster-api
    def post_new_snippet():

        if not has_scope("post:snippet"):
            abort(403)

        body = request.get_json()

        coderId = body.get('coderId', None)
        coder = Coder.query.get(coderId)

        if not coder:
            abort(404)

        attrs = {}
        attrs['snippet_name'] = body.get('name', None)
        attrs['code'] = body.get('code', None)
        attrs['needs_review'] = body.get('needsReview', False)
        attrs['comments'] = body.get('comments', '')

        if attrs['snippet_name'] and attrs['code']:
            try:
                snippet = Snippet(**attrs)
                # insert snippet by appending as a child to its coder and
                # updating coder
                coder.snippets.append(snippet)
                coder.update()
                return jsonify({
                    "success":
                    True,
                    "message":
                    "Snippet has been successfully saved to database"
                })
            except:
                abort(500)

        else:
            abort(400)
コード例 #22
0
ファイル: util.py プロジェクト: yanokwa/snippets
def most_recent_snippet_for_user(user_email):
    """Return the most recent snippet for a given user, or None."""
    snippets_q = Snippet.all()
    snippets_q.filter('email = ', user_email)
    snippets_q.order('-week')            # this puts newest snippet first
    return snippets_q.get()
コード例 #23
0
ファイル: util.py プロジェクト: yanokwa/snippets
def snippets_for_user(user_email):
    """Return all snippets for a given user, oldest snippet first."""
    snippets_q = Snippet.all()
    snippets_q.filter('email = ', user_email)
    snippets_q.order('week')            # this puts oldest snippet first
    return snippets_q.fetch(1000)       # good for many years...
コード例 #24
0
ファイル: views.py プロジェクト: jettagozoom/AngularSomecode
def snippets(topic):
    if request.method == 'POST':
        """ Save a new snippet """
        # See if the topic exists
        topic = g.user.topics.filter_by(topic=topic).first()
        if topic is None:
            return jsonify(error=404, text='Invalid topic name'), 404

        # Get the snippet data from the request
        if (request.data):
            data = json.loads(request.data)
        access = ACCESS_PRIVATE;
        if data.get('access') == True:
            access = ACCESS_PUBLIC;
        title = data['title']
        description = data['description']
        code = data['code']
        language = data['language']

        # Persist the snippet to the users topic
        snippet = Snippet(title = title, description = description, code = code,
                          timestamp = datetime.utcnow(), topic = topic,
                          creator_id = g.user.id, language = language, access = access)
        db.session.add(snippet)
        db.session.commit()

        d = dict(title = snippet.title, description = snippet.description, code = snippet.code,
                 language = snippet.language, access = snippet.access,
                 creator_id = snippet.creator_id, id = snippet.id,
                 topic = snippet.topic.topic, snippet_counts = getSnippetCounts())
        return Response(json.dumps(d), 200, mimetype="application/json")

    elif request.method == 'PUT':
        """ Update an existing snippet """
        snippet_id = int(topic)
        topics = g.user.topics
        snippet = None
        for topic in topics:
            snippet = topic.snippets.filter_by(id=snippet_id).first()
            if snippet != None:
                break;

        if snippet == None:
            return jsonify(error=404, text='Invalid snippet ID'), 404

        if (request.data):
            data = json.loads(request.data)
        #pdb.set_trace()
        access = ACCESS_PRIVATE;
        if data.get('access') == True:
            access = ACCESS_PUBLIC;

        snippet.title = data['title']
        snippet.description = data['description']
        snippet.code = data['code']
        snippet.access = access
        snippet.language = data['language']
        db.session.commit()
        return jsonify(id = snippet.id, creator_id = snippet.creator_id, access = snippet.access, snippet_counts = getSnippetCounts())

    elif request.method == 'GET':
        """ Find all snippets associated with a topic """
        # Find the topic
        topic = g.user.topics.filter_by(topic=topic).first()
        if topic is None:
            return jsonify(error=404, text='Invalid topic name'), 404

        # Get all snippets in the topic
        snippets = topic.snippets.order_by(Snippet.timestamp.desc()).all()
        snippetList = []
        for i, snip in enumerate(snippets):
            d = dict(title = snip.title, description = snip.description, code = snip.code,
                     language = snip.language, access = snip.access,
                     creator_id = snip.creator_id, id = snip.id, topic = snip.topic.topic)
            snippetList.append(d)

        return Response(json.dumps(snippetList), 200, mimetype="application/json")

    elif request.method == 'DELETE':
        """ Delete a snippet """
        snippet_id = int(topic)
        topics = g.user.topics
        snippet = None
        for topic in topics:
            snippet = topic.snippets.filter_by(id=snippet_id).first()
            if snippet != None:
                break;

        if snippet == None:
            return jsonify(error=404, text='Invalid snippet ID'), 404

        topicName = snippet.topic.topic
        if snippet.ref_count == 1:
            db.session.delete(snippet)
            db.session.commit()
        else:
            snippet.dec_ref()
            db.session.commit()
        return jsonify({'id':snippet_id, 'topic':topicName, 'snippet_counts':getSnippetCounts()})
コード例 #25
0
 def render(self):
     id = self.request.get("id")
     key = ndb.Key("Snippets", long(id))
     snippet = Snippet.get_by_id(long(id))
     snippet.key.delete()
     self.list()
コード例 #26
0
ファイル: initdb.py プロジェクト: liquiddandruff/booksnipptr
    db.session.add(tag_tragedy)
    db.session.add(tag_novel)
    db.session.add(tag_adventure_fic)
    db.session.add(tag_classic_lit)
    db.session.add(tag_horror)
    db.session.add(tag_poetry)
    db.session.add(tag_romance)
    db.session.add(tag_fantasy)
    db.session.add(tag_scifi)
    db.session.add(tag_crime)
    #vim macro buffer yiwodb.session.add()Pdd}p``

    snippet_lotr = Snippet(title="Lord of the Rings", author="J.R.R. Tolkien",
                           content = "It's a dangerous business, Frodo, going out your door.\
                                      You step onto the road, and if you don't keep your feet, there's no knowing where \
                                      you might be swept off to.",
                           tags=[tag_fantasy, tag_classic_lit], \
                           created_at=(datetime.utcnow() - timedelta(days=1)))
    db.session.add(snippet_lotr)

    snippet_ringWorld = Snippet(title="Ringworld", author="Larry Niven",
                                content = "The gods do not protect fools. Fools are protected by more capable fools.",
                                tags=[tag_scifi])
    db.session.add(snippet_ringWorld)

    snippet_outlander = Snippet(title="Outlander", author="Diana Gabaldon", 
                                content = "Don't be afraid. There's the two of us now.",
                                tags=[tag_romance, tag_scifi])
    db.session.add(snippet_outlander)

    user_zhilinz = User(username="******", tags=[tag_scifi, tag_fantasy, tag_horror])
コード例 #27
0
 def process(self):
     id = self.request.get("id")
     snippet = Snippet.get_by_id(long(id))
     self.put(snippet)
     self.list()
コード例 #28
0
class TestSnippetAPIViewsUsingAPIClient(APITestCase):
    """
    Test the SnippetViewSet using APIClient
    Note: self.client is an instance of the rest framework's APIClient
    """

    fixtures = ['initial_data']

    def setUp(self):
        self.test_snippet = Snippet(title="test snippet", code="some code",
                                    owner=User.objects.get(username="******"))
        self.test_snippet.save()

    def test_highlight(self):
        """Test the 'highlight' action."""
        url = reverse('snippet-highlight', args=[self.test_snippet.pk])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertIn("<html>", response.data)
        self.assertIn(self.test_snippet.title, response.data)

    def test_detail(self):
        """Snippet details may be retrieved without logging in"""
        url = reverse('snippet-detail', args=[self.test_snippet.pk])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['owner'],
                         self.test_snippet.owner.username)

    def test_list(self):
        """Snippet list may be retrieved without logging in"""
        url = reverse('snippet-list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['count'], 1)

    def test_create_snippet_not_logged_in(self):
        """Must be logged in to create a snippet"""
        url = reverse('snippet-list')
        response = self.client.post(url,
                                    {'title': 'should fail', 'code': 'asdf'},
                                    format='json')
        self.assertEqual(response.status_code, 403)

    def test_create_snippet_logged_in(self):
        """Logged in users may create snippets"""
        url = reverse('snippet-list')
        self.client.force_authenticate(user=User.objects.get(username="******"))
        response = self.client.post(url, {'title': 'should work',
                                          'code': 'some code'})
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['code'], 'some code')

    def test_delete_snippet_not_logged_in(self):
        """Only the owner may delete a snippet"""
        url = reverse('snippet-detail', args=[self.test_snippet.pk])
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 403)

    def test_delete_snippet_owner_logged_in(self):
        """The owner of a snippet may delete it"""
        url = reverse('snippet-detail', args=[self.test_snippet.pk])
        self.client.force_authenticate(user=User.objects.get(username="******"))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 204)

    def test_delete_snippet_wrong_user(self):
        """Users may not delete another users snippets"""
        url = reverse('snippet-detail', args=[self.test_snippet.pk])
        self.client.force_authenticate(user=User.objects.get(username="******"))
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 403)
コード例 #29
0
ファイル: open_module.py プロジェクト: guardian/open-module
 def render(self):
     id = self.request.get("id")
     key = ndb.Key("Snippets", long(id) )
     snippet = Snippet.get_by_id(long(id))
     snippet.key.delete()
     self.list()
コード例 #30
0
ファイル: open_module.py プロジェクト: guardian/open-module
 def render(self):
    id = self.request.get("id")
    snippet = Snippet.get_by_id(long(id))
    template = jinja_environment.get_template("preview.html")
    self.response.out.write(template.render(snippet=snippet, id=id))
コード例 #31
0
 def process(self):
     snippet = Snippet()
     self.put(snippet)
     self.redirect('/list')
コード例 #32
0
 def render(self):
     id = self.request.get("id")
     snippet = Snippet.get_by_id(long(id))
     template = jinja_environment.get_template("preview.html")
     self.response.out.write(template.render(snippet=snippet, id=id))
コード例 #33
0
ファイル: views.py プロジェクト: jettagozoom/MVP
def snippets(topic):
    if request.method == 'POST':
        """ Save a new snippet """
        # See if the topic exists
        topic = g.user.topics.filter_by(topic=topic).first()
        if topic is None:
            return jsonify(error=404, text='Invalid topic name'), 404

        # Get the snippet data from the form
        if (request.form):
            form = request.form.to_dict()
        access = ACCESS_PRIVATE;
        if form.get('access') == 'on':
            access = ACCESS_PUBLIC;
        title = form['title']
        description = form['description']
        code = form['code']

        # Persist the snippet to the users topic
        snippet = Snippet(title = title, description = description, code = code,
                          timestamp = datetime.utcnow(), topic = topic,
                          creator_id = g.user.id, access = access)
        db.session.add(snippet)
        db.session.commit()
        return jsonify(id = snippet.id, creator_id = snippet.creator_id, access = snippet.access)

    elif request.method == 'PUT':
        """ Update an existing snippet """
        snippet_id = topic
        topics = g.user.topics
        snippet = None
        for topic in topics:
            snippet = topic.snippets.filter_by(id=snippet_id).first()
            if snippet != None:
                break;

        if snippet == None:
            return jsonify(error=404, text='Invalid snippet ID'), 404

        if (request.form):
            form = request.form.to_dict()
        access = ACCESS_PRIVATE;
        if form.get('access') == 'on':
            access = ACCESS_PUBLIC;
        title = form['title']
        description = form['description']
        code = form['code']

        snippet.title = title;
        snippet.description = description;
        snippet.code = code;
        snippet.access = access;
        db.session.commit()
        return jsonify(id = snippet.id, creator_id = snippet.creator_id, access = snippet.access)

    elif request.method == 'GET':
        """ Find all snippets associated with a topic """
        # Find the topic
        topic = g.user.topics.filter_by(topic=topic).first()
        if topic is None:
            return jsonify(error=404, text='Invalid topic name'), 404

        # Get all snippets in the topic
        snippets = topic.snippets.order_by(Snippet.timestamp.desc()).all()
        reply = {}
        for i, snip in enumerate(snippets):
            d = dict(title = snip.title, description = snip.description, code = snip.code,
                     access = snip.access, creator_id = snip.creator_id, id = snip.id)
            reply[i] = d

        return jsonify(reply)

    elif request.method == 'DELETE':
        """ Delete a snippet """
        snippet_id = topic
        topics = g.user.topics
        snippet = None
        for topic in topics:
            snippet = topic.snippets.filter_by(id=snippet_id).first()
            if snippet != None:
                break;
        
        if snippet == None:
            return jsonify(error=404, text='Invalid snippet ID'), 404

        if snippet.ref_count == 1:
            db.session.delete(snippet)
            db.session.commit()
            return jsonify(id=snippet.id)
        else:
            snippet.dec_ref()
            db.session.commit()
            return jsonify(id=0)
コード例 #34
0
ファイル: open_module.py プロジェクト: guardian/open-module
 def process(self):
     id = self.request.get("id")
     snippet = Snippet.get_by_id(long(id))
     self.put(snippet)
     self.list()
コード例 #35
0
#----------------------------
# Populate the database
#----------------------------

tag_cool = Tag(name='cool')
tag_car = Tag(name='car')
tag_animal = Tag(name='animal')

comment_rhino = Comment(
    text=
    'Rhinoceros, often abbreviated as rhino, is a group of five extant species of odd-toed ungulates in the family Rhinocerotidae.'
)

snippet_car = Snippet(content='This is a post about a car.', \
    tags=[tag_car, tag_cool], \
    created_at=(datetime.utcnow() - timedelta(days=1)))

snippet_another_car = Snippet(content='This is a post about another car.', \
    tags=[tag_car])

snippet_rhino = Snippet(content='Rhinos have a big horn on their face.', \
    tags=[tag_animal], \
    comments=[comment_rhino])

user_joe = User(uuid='Joe blow from cokamoe',
                tags=[tag_car, tag_cool, tag_animal])

# Create a new Session and add the posts:
session = Session()
コード例 #36
0
class TestSnippetAPIViewsUsingAPIRequestFactory(APITestCase):
    """Test the SnippetViewSet using APIRequestFactory"""

    fixtures = ['initial_data']

    def setUp(self):
        self.factory = APIRequestFactory()
        self.test_snippet = Snippet(title="test snippet", code="some code",
                                    owner=User.objects.get(username="******"))
        self.test_snippet.save()

    def test_highlight(self):
        """Test the 'highlight' action."""
        view = SnippetViewSet.as_view({'get': 'highlight'})
        request = self.factory.get('/snippets/000/highlight')
        response = view(request, pk=self.test_snippet.pk)
        self.assertEqual(response.status_code, 200)
        self.assertIn("<html>", response.data)
        self.assertIn(self.test_snippet.title, response.data)

    def test_detail(self):
        """Snippet details may be retrieved without logging in."""
        view = SnippetViewSet.as_view({'get': 'retrieve'})
        request = self.factory.get('/snippets/000')
        response = view(request, pk=self.test_snippet.pk)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['owner'],
                         self.test_snippet.owner.username)

    def test_list(self):
        """Snippet list may be retrieved without logging in"""
        view = SnippetViewSet.as_view({'get': 'list'})
        request = self.factory.get('/snippets')
        response = view(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['count'], 1)

    def test_create_snippet_not_logged_in(self):
        """Must be logged in to create a snippet"""
        view = SnippetViewSet.as_view({'post': 'create'})
        request = self.factory.post('/snippets',
                                    data={'title': 'should fail',
                                          'code': 'asdf'})
        response = view(request)
        self.assertEqual(response.status_code, 403)

    def test_create_snippet_logged_in(self):
        """Logged in users may create snippets"""
        view = SnippetViewSet.as_view({'post': 'create'})
        request = self.factory.post('/snippets',
                                    data={'title': 'should work',
                                          'code': 'some code'})
        force_authenticate(request, user=User.objects.get(username="******"))
        response = view(request)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['code'], 'some code')

    def test_delete_snippet_not_logged_in(self):
        """Only the owner may delete a snippet"""
        view = SnippetViewSet.as_view({'delete': 'destroy'})
        request = self.factory.delete('/snippets/000')
        response = view(request, pk=self.test_snippet.pk)
        self.assertEqual(response.status_code, 403)

    def test_delete_snippet_owner_logged_in(self):
        """The owner of a snippet may delete it"""
        view = SnippetViewSet.as_view({'delete': 'destroy'})
        request = self.factory.delete('/snippets/000')
        force_authenticate(request, user=User.objects.get(username="******"))
        response = view(request, pk=self.test_snippet.pk)
        self.assertEqual(response.status_code, 204)

    def test_delete_snippet_wrong_user(self):
        """Users may not delete another users snippets"""
        view = SnippetViewSet.as_view({'delete': 'destroy'})
        request = self.factory.delete('/snippets/000')
        force_authenticate(request, user=User.objects.get(username="******"))
        response = view(request, pk=self.test_snippet.pk)
        self.assertEqual(response.status_code, 403)
コード例 #37
0
 def setUp(self):
     self.factory = APIRequestFactory()
     self.test_snippet = Snippet(title="test snippet", code="some code",
                                 owner=User.objects.get(username="******"))
     self.test_snippet.save()