如何在 Google App Engine (Python) 中使用 AJAX [英] How to use AJAX with Google App Engine (Python)

查看:28
本文介绍了如何在 Google App Engine (Python) 中使用 AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 AJAX 完全是新手.我熟悉 HTML/CSS、jQuery 以及 GAE 和 Python 的初学者.

为了理解 AJAX 的工作原理,我想知道在下面的示例中如何使用 AJAX(实际代码).让我们使用一个类似 reddit 的例子,其中投票上升/下降被 ajaxified:

这是故事类型:

class Story(ndb.Model):标题 = ndb.StringProperty(required = True)投票计数 = ndb.IntegerProperty(默认 = 0)

HTML 看起来像这样:

{{story.title}}

<div>{{story.vote_count}} |<a href="#">投票故事</a>

AJAX 在这里是如何适应的?

解决方案

好的,我们开始吧...一个简单的应用程序,有一个故事和无限的投票...;-)

app.yaml

application: anotherappname版本:1运行时:python27api_version: 1线程安全:真default_expiration: "0d 0h 5m"图书馆:- 名称:jinja2版本:最新- 名称:webapp2版本:最新处理程序:- 网址:.*脚本:main.app

main.py

导入日志从控制器导入服务器从配置导入配置导入 webapp2app = webapp2.WSGIApplication([# 基本处理程序('/', server.RootPage),('/vote/', server.VoteHandler)],debug=True, config=config.config)# 额外的处理程序,如 404 500 等def handle_404(请求,响应,异常):logging.exception(异常)response.write('Oops! Naughty Mr. Jiggles (This is a 404)')response.set_status(404)app.error_handlers[404] = handle_404

models/story.py

 from google.appengine.ext import ndb类故事(ndb.Model):标题 = ndb.StringProperty(required=True)投票计数 = ndb.IntegerProperty(默认 = 0)

controllers/server.py

导入操作系统进口重新导入日志导入配置导入json导入 webapp2进口jinja2从 google.appengine.ext 导入 ndb从models.story导入故事类 RootPage(webapp2.RequestHandler):定义获取(自我):story = Story.get_or_insert('Some id or so', title='再次投票的故事...')jinja_environment = self.jinja_environment模板 = jinja_environment.get_template("/index.html")self.response.out.write(template.render({'story': story}))@财产def jinja_environment(self):jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'../视图')))返回 jinja_environment类 VoteHandler(webapp2.RequestHandler):定义帖子(自我):logging.info(self.request.body)数据 = json.loads(self.request.body)story = ndb.Key(Story, data['storyKey']).get()story.vote_count += 1故事.put()self.response.out.write(json.dumps(({'story': story.to_dict()})))

最后

views/index.html

<头><base href="/"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><身体><h2>{{story.title}}</h2><div><span class="voteCount">{{story.vote_count}}</span>|<a href="javascript:VoteUp('{{story.key.id()}}');">投票故事</a>

<脚本>功能投票(故事键){$.ajax({类型:POST",网址:/投票/",数据类型:'json',数据:JSON.stringify({storyKey":storyKey})}).done(function(data) {//检查我为什么使用 done警报(投票!!!计数是:"+数据['故事']['vote_count']);$('.voteCount').text(data['story']['vote_count']);});};

组装,阅读它很简单,然后运行.如果您需要一个有效的 git 示例,请发表评论.

githublink(来自评论)

I am completely novice at AJAX. I am familiar with HTML/CSS, jQuery and beginner at GAE and Python.

In an effort to understand how AJAX works, I would like to know how AJAX might be used (actual code) in this example below. Let's use a reddit-like example where vote ups/downs are ajaxified:

Here is the Story Kind:

class Story(ndb.Model):
    title = ndb.StringProperty(required = True)
    vote_count = ndb.IntegerProperty(default = 0)

The HTML would look like this:

<h2>{{story.title}}</h2>
<div>
    {{story.vote_count}} | <a href="#">Vote Up Story</a>
</div>

How does AJAX fit inside here?

解决方案

Ok Sir here we go... A simple app with one story and infinite votes... ;-)

app.yaml

application: anotherappname
version: 1
runtime: python27
api_version: 1
threadsafe: true

default_expiration: "0d 0h 5m"

libraries:
- name: jinja2
  version: latest

- name: webapp2
  version: latest

handlers:
- url: .*
  script: main.app

main.py

import logging
from controllers import server
from config import config
import webapp2


app = webapp2.WSGIApplication([
        # Essential handlers
        ('/', server.RootPage),
        ('/vote/', server.VoteHandler)
    ],debug=True, config=config.config)


# Extra Hanlder like 404 500 etc
def handle_404(request, response, exception):
    logging.exception(exception)
    response.write('Oops! Naughty Mr. Jiggles (This is a 404)')
    response.set_status(404)

app.error_handlers[404] = handle_404

models/story.py

from google.appengine.ext import ndb


class Story(ndb.Model):
    title = ndb.StringProperty(required=True)
    vote_count = ndb.IntegerProperty(default = 0)

controllers/server.py

import os
import re
import logging
import config
import json

import webapp2
import jinja2

from google.appengine.ext import ndb
from models.story import Story


class RootPage(webapp2.RequestHandler):
    def get(self):
        story = Story.get_or_insert('Some id or so', title='A voting story again...')
        jinja_environment = self.jinja_environment
        template = jinja_environment.get_template("/index.html")
        self.response.out.write(template.render({'story': story}))


    @property
    def jinja_environment(self):
        jinja_environment = jinja2.Environment(
            loader=jinja2.FileSystemLoader(
                os.path.join(os.path.dirname(__file__),
                             '../views'
                ))
        )
        return jinja_environment


class VoteHandler(webapp2.RequestHandler):
    def post(self):
        logging.info(self.request.body)
        data = json.loads(self.request.body)
        story = ndb.Key(Story, data['storyKey']).get()
        story.vote_count += 1
        story.put()
        self.response.out.write(json.dumps(({'story': story.to_dict()})))

and finally

views/index.html

<!DOCTYPE html>
<html>
    <head>
        <base href="/">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    </head>
    <body>
        <h2>{{story.title}}</h2>
        <div>
            <span class="voteCount">{{story.vote_count}}</span>  | <a href="javascript:VoteUp('{{story.key.id()}}');" >Vote Up Story</a>
        </div>
        <script>
            function VoteUp(storyKey){
                $.ajax({
                  type: "POST",
                  url: "/vote/",
                  dataType: 'json',
                  data: JSON.stringify({ "storyKey": storyKey})
                })
                .done(function( data ) { // check why I use done
                    alert( "Vote Cast!!! Count is : " + data['story']['vote_count'] );
                    $('.voteCount').text(data['story']['vote_count']);
                });
            };
        </script>
    </body>
</html>

Assemble, read it's simple enough and run. If you need a working git example just comment.

githublink (as from comments)

这篇关于如何在 Google App Engine (Python) 中使用 AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆