写在Web考试后的一点小总结

在实验室折腾附加题折腾了一个多钟没做出来……晚上回到宿舍决定再试一试,按原来的思路居然行了,目测在实验室的时候什么地方打错字了吧(心在流血)

实现晃过元素后出现跟随鼠标的悬浮窗,只有几行代码给我折腾了好久,前端的JS果然debug困难 打错字都没提示OTZ 下次试试strict mode好了……

简而言之就是mouseover的时候show,mouseout的时候hide,mousemove的时候跟着改坐标

// tweet.js

$('#avatar').mouseover(function(e){
    $('#tip').show();
});

$('#avatar').mousemove(function(e){
    var offset = $('#avatar').offset();
    var x = e.pageX - offset.left + 10;
    var y = e.pageY - offset.top + 10;
    $('#tip').css({"left": x + "px", top: y + "px"});
});

$('#avatar').mouseout(function(e){
    $('#tip').hide();
});

在实验室的时候贪方便,数据库操作写到其他函数里,连接的代码复制粘贴重复了N遍,回去重新写了一下,直接放到application里,大家一起用:

#main.py

conn = pymongo.Connection("localhost", 27017)
twitterDB=conn["twitterDB"]
self.db = twitterDB.userSets

用的时候直接写self.application.db就可以了。因为userinfo只有一个instance,为了效率包数据的时候用namedtuple代替了class(看了知乎一个实习生笔试被拒的问答之后对“过度封装"格外敏感……),mongodb的查询回来之后被我改成了用projection提高效率(其实第二个抓tweets的操作也可以用projection的不过懒得写了……)

# main.py

class MainPageHandler(BaseHandler):
    """Handle the main page."""
    def get(self, index):
        # retrieve data from local database
        user = self.get_current_user()
        # project user info and put it into a dict
        info_dict = self.application.db.find_one({"name": user},
            {"_id": 0, "name": 1, "image": 1, "age": 1, "email": 1})
        # get tweets of the user
        tweets = self.application.db.find_one({"name": user})['tweets']

        # Since there's only one user per page, use namedtuple
        info = namedtuple('Info', info_dict.keys())(*info_dict.values())

        self.render('twitter.html', info=info, tweets=tweets, user=user)

AJAX操作方面用Jquery搞定,Prototype比较没那么灵活的样子(JSON一定要写清楚类型),不过安全起见还是多给header设置了几句。在TA的提示下给提交后的callback加了清空文本框,稍微自然一点。

实验室只有chrome,拿回去测试的时候发现FF下不行,看log发现点按钮之后给定的AJAX POST专用的url没动静,反而原来页面的url有个不成功的POST,也就是event.preventDefault()没有起到作用。google了一下发现是FF没有全局的event,所以不能写$("#submitTweet").click(function(){}),必须写$("#submitTweet").click(function(event){}),不然里面的函数拿不到event就取消不了按钮按下去的缺省效果

$("#submitTweet").click(function(event) {
    event.preventDefault();
    var tweet = {
        time: $.datepicker.formatDate('M. dd, yy', new Date()),
        content: $('#tweet-content').val()
    };

    $.ajax({
            url: '/ajax/addTweet',
            datatype: "json",
            type: "POST",
            data: JSON.stringify(tweet),
            contentType: "application/json charset=utf-8",
            processData: false,
            success: function (data) {
                insertTweet(tweet.time, tweet.content);
                $('#tweet-content').val('');
            },
            error: function(e){
                alert(e);
            }
    });
});

后端用了tornado自带的json_decode,忘了之前做什么东西的时候被py自带的json.loads坑过,用tornado带的比较安全一点

class addTweet(BaseHandler):
    """Get tweet posted with AJAX and save it to the local database."""
    def post(self):
        newTweet = tornado.escape.json_decode(self.request.body)
        user = self.get_current_user()
        record = self.application.db.find_one({"name": user})
        record['tweets'].append(newTweet)
        self.application.db.save(record)

为了方便debug写了几个print语句,会夹进log显示在终端, 方便看到数据库操作结果。有空试试看学着用logging,不要直接print……

另外回来之后帮人debug,发现好多人有出错不仔细看log啊= =b

考试之前还写了个自定义的404,关键在于给其他RequestHandler继承的类里面要记得定义get_error_html,并且这个函数不能用render,要用render_string,不过写法还是一样,模版放在老地方

class BaseHandler(tornado.web.RequestHandler):
    def get_error_html(self, status_code, **kwargs):
        return self.render_string("404.html",
            err=kwargs.get('message', None))

然后在RequestHandler里有需要丢404的地方写

self.send_error(404, **error)

就可以了。其他状态码同理,加if语句配置就行。不想全都继承的话在只有需要的类里面定义get_error_html也OK。

代码依然在Github上

https://github.com/joyeec9h3/WebHWs/tree/master/Web2_0course

原文地址:https://www.cnblogs.com/joyeecheung/p/3499415.html