1

だから私はPythonで次のコードGAEコードを持っています、そしてそれは少し長いです、しかし基本的にそれはユーザーがブログに投稿することを可能にしそしてそれからユーザーがリダイレクトされるパーマリンクに各ブログ投稿を保存しそしてユーザーは永遠に再リンクすることができます。パーマリンクのURLは単なるblog/(ブログ投稿ID)です。したがって、パーマリンクはリダイレクトメソッドによってNewPostハンドラーで作成され(間違っている場合は修正してください)、これらのパーマリンクのリストはどこに保存されていますか?どういうわけかアクセスできますか?視覚的に見えないので、この部分が少しつまずきます。

私はUdacity.comからこのすべてのコードを学びましたが、彼らはこの点を実際には説明しておらず、私はそれを機能させることができますが、それがどのように機能するかを理解していません。

import os
import re
from string import letters

import webapp2
import jinja2

from google.appengine.ext import db

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape = True)

def render_str(template, **params):
    t = jinja_env.get_template(template)
    return t.render(params)

class BlogHandler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, template, **params):
        return render_str(template, **params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

def render_post(response, post):
    response.out.write('<b>' + post.subject + '</b><br>')
    response.out.write(post.content)

#front page
class MainPage(BlogHandler):
  def get(self):
      self.write('Hello, Udacity!')

def blog_key(name = 'default'):
    return db.Key.from_path('blogs', name)

#creates the database
class Post(db.Model):
    subject = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)
    last_modified = db.DateTimeProperty(auto_now = True)

    def render(self):
        self._render_text = self.content.replace('\n', '<br>')
        return render_str("post.html", p = self)

#front of blog with list of last 10 posts
class BlogFront(BlogHandler):
    def get(self):
        posts = db.GqlQuery("select * from Post order by created desc limit 10")
        self.render('front.html', posts = posts)

#displays the permalink page
class PostPage(BlogHandler):
    def get(self, post_id):
        key = db.Key.from_path('Post', int(post_id), parent=blog_key())
        post = db.get(key)

        if not post:
            self.error(404)
            return

        self.render("permalink.html", post = post)

#create a new post
class NewPost(BlogHandler):
    def get(self):
        self.render("newpost.html")

    def post(self):
        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            p = Post(parent = blog_key(), subject = subject, content = content)
            p.put()
            self.redirect('/blog/%s' % str(p.key().id()))
        else:
            error = "subject and content, please!"
            self.render("newpost.html", subject=subject, content=content, error=error)


app = webapp2.WSGIApplication([('/', MainPage),
                               ('/unit2/welcome', Welcome),
                               ('/blog/?', BlogFront),
                               ('/blog/([0-9]+)', PostPage),
                               ('/blog/newpost', NewPost),
                               ],
                              debug=True)

アップデート:

次の方法でコードを変更して、検索エンジンをもう少し使いやすくすることは可能でしょうか。

class NewPost(BlogHandler):
    def get(self):
        self.render("newpost.html")

    def post(self):
        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            p = Post(parent = blog_key(), subject = subject, content = content)
            p.put()
            #the change is in the following line:
            self.redirect('/blog/%s/%s' % (str(p.key().id(), str(p.subject)))
        else:
            error = "subject and content, please!"
            self.render("newpost.html", subject=subject, content=content, error=error)

最終更新:

次のコードを使用して、検索エンジンをより使いやすくするという問題を解決しました。

 def post(self):
            subject = self.request.get('subject')
            content = self.request.get('content')

        if subject and content:
            p = Post(parent = blog_key(), subject = subject, content = content)
            p.put()
            subject = p.subject
            subject = subject.replace(' ', '25fdsa67ggggsd5')
            subject = ''.join(e for e in subject if e.isalnum())
            subject = subject.replace('25fdsa67ggggsd5', '-')
            subject = subject.lower()
            self.redirect('/blog/%s/%s' % (str(p.key().id(), str(subject)))
        else:
            error = "subject and content, please!"
            self.render("newpost.html", subject=subject, content=content, error=error)
4

1 に答える 1

3

ブログ投稿のIDは、データストアの前で取得するために必要なすべてであるため、いかなる種類のマッピングも必要ありません。リクエストはパーマリンクURLで受信され、IDはURLから抽出され、投稿はIDを使用してデータストアから取得され、ブログ投稿がレンダリングされます。

これはシンプルで効果的な戦略ですが、失敗する領域の1つは検索エンジン最適化です。ほとんどの検索エンジンは、数字や文字の文字列ではなく、単語を含むURLを好みます。

これは一般にスラッギングと呼ばれ、IDと文字列の間のマッピングを提供する必要があります。数年前、私はAppEngine / Pythonプログラムに簡単なスラッギングを提供するミックスインクラスを作成しました:sluggable-mixin。それでも動作するはずです。

于 2012-06-20T18:41:39.210 に答える