Archive for web-2

scrapy安装确实麻烦,网上找到一片详细按照教程保存下来。安装scrapy的方法详解下载地址:安装scrapy的方法详解

Continue

非常简单实用的方法,收藏了。这几天写的东西没用jquery,但是有些功能还是想从简,比如这个提示是否删除。最简单的方法还是只是弹个提示框,于是找到这个方法。 JavaScript弹出确认消息框判断是否删除,删除前提示用户是否删除,点是删除,点否返回。

删除
用法:onClick="return confirm('是否删除此条记录?')" onClick在点击时(这里是指点击这条超链接)触发,confirm会返回“是”(true)或者“否”(false),返回“否”就不产生跳转。 原来这个js中return可以控制超链接是否跳转啊,神奇,嘿嘿,忒神奇了~

Continue

真心不懂css,以前写点小东西,不是扒就是用的bootstrap。现在要我自己写一个支持ie6的界面,有点慌。 bootstrap是只支持ie7+,虽然有写ie6的hack,可能是我用的不好,效果不喜欢。 自己大体测试了一下,ie6不支持bootstrap中的布局方面和组件那些导航什么的。 http://twitter.github.com/bootstrap 现在bootstrap网站提供自己制定功能,可以选择自己使用的css功能,我只用了Base CSS和Alerts,再有需要就重新添加导出一份。网站布局的设定我就找了一个1kbgrid,http://www.1kbgrid.com/。很方便,很小。配合使用写了三个页面感觉很不错。 css设计也是一门艺术,但是第一次学时可能教材不好,安不下心来感觉很乱。以后就不再想学了。

Continue

apache在本机上访问正常,但是用ip访问为403禁止访问! apache配置文件修改: # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride all # # Controls who can get stuff from this server. # # onlineoffline tag - don't remove Order Deny,Allow Deny from all Allow from 127.0.0.1 Allow from 127.0.0.1修改为Allow from all,没有查文档,搜索解决。

Continue

在wamp下的开发环境,查找资料有两种方法。使用query,使用prepare。看的代码是第二种,网上说第二种效率高,并且安全。 总结使用方法:  

$sth = $dbh->prepare('update db set zh_CN= :str where SN=:SN');
$sth->bindParam(':str',$str,PDO::PARAM_STR,12);
$sth->bindParam(':SN',$SN);
$sth->execute();
$sth->lastInsertId();
$sth->closeCursor();
源代码使用bindValue(),lastInsertId()返回id。

Continue

安装时没有安装桌面环境。 1.查看centos系统版本:命令lbs_release -a 2.mysql配置。 mysql从安装光盘中选择安装的。版本是5.0.77 修改/etc/my.cnf文件 default-character-set=utf8 [mysqld] datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock user=mysql # Default to using old password format for compatibility with mysql 3.x # clients (those using the mysqlclient10 compatibility package). old_passwords=1 default-character-set=utf8 增加 [mysqld_safe] log-error=/var/log/mysqld.log pid-file=/var/run/mysqld/mysqld.pid [mysql] 增加 default-character-set=utf8 增加 没有密码登录时使用命令:mysql -u root 启动mysql服务:/etc/rc.d/init.d/mysqld start 设置密码 /usr/bin/mysqladmin -u root password '123456'   3.安装Apahce # yum -y install httpd php php-mysql 安装php的扩展 #yum -y install php-gd php-xml php-mbstring php-ldap php-pear php-xmlrpc 安装apache扩展 #yum -y install httpd-manual mod_ssl mod_perl mod_auth_mysql chkconfig httpd on [设置apache为自启动] service httpd start [启动 httpd 服务] apache配置出来的默认站点目录为/var/www/html/   4.测试 # vi /var/www/html/info.php <?php phpinfo(); ?> 命令行下输入:firefox,打开浏览器。输入http://127.0.0.1,可以显示欢迎界面,加上info.php,可以显示php的环境信息。    

Continue

django中csrf的验证: Django是在post中有一个字段CsrfViewMiddleware 进行相关验证,验证过程很简单,从Cookie中拿出token,然后从POST中拿出csrfmiddlewaretoken,然后块俩做一个字符匹配。因为恶意网站无法读取你的Cookie(因为浏览器的同源策略),所以无法获得Cookie里的CSRF Token,无法伪造出csrf,POST就会失败,这样就不会产生安全问题。 ajax提交post表单时,从网上找到一个感觉不错的方法记录。

function getCookie(sName){
var aCookie=document.cookie.split("; ");
for(var i=0;i<aCookie.length;i++){var aCrumb=aCookie[i].split("=");if(sName==aCrumb[0])
return(aCrumb[1]);}return null;}
在需要提交表单的地方,加入的数据是getCookie('csrftoken') 字段名为csrfmiddlewaretoken

Continue

很简单的代码,记录一下。

    import Image
    image = Image.open('a.jpg')
    import cStringIO
    buf = cStringIO.StringIO()
    image.save(buf, image.format,quality=75)
    data = buf.getvalue()
    a = u.writeFile('/this/logo.jpg',data,True)
应用在 使用django,用户上传图片后,将图片转存到别的服务器。但是转存需要对图片进行处理,但是quality设定的保存,不知道可不可以在不是image.save()的时候。写的这个是保存时放到内存,然后直接提交到图片服务器。

Continue

当需要将上传的文件保存到别的服务器,而又不修改views里的代码,下面可能对你有点用。 Python26\Lib\site-packages\django\core\files\storage.py 这个文件里有一个FileSystemStorage类,类里的函数_save()进行了上传文件的保存。先上代码:

    def _save(self, name, content):
        full_path = self.path(name)
        print full_path,name
        # Create any intermediate directories that do not exist.
        # Note that there is a race between os.path.exists and os.makedirs:
        # if os.makedirs fails with EEXIST, the directory was created
        # concurrently, and we can continue normally. Refs #16082.
        directory = os.path.dirname(full_path)
        if not os.path.exists(directory):
            try:
                os.makedirs(directory)
            except OSError, e:
                if e.errno != errno.EEXIST:
                    raise
        if not os.path.isdir(directory):
            raise IOError("%s exists and is not a directory." % directory)

        # There's a potential race condition between get_available_name and
        # saving the file; it's possible that two threads might return the
        # same name, at which point all sorts of fun happens. So we need to
        # try to create the file, but if it already exists we have to go back
        # to get_available_name() and try again.

        while True:
            try:
                # This file has a file path that we can move.
                if hasattr(content, 'temporary_file_path'):
                    file_move_safe(content.temporary_file_path(), full_path)
                    content.close()

                # This is a normal uploadedfile that we can stream.
                else:
                    # This fun binary flag incantation makes os.open throw an
                    # OSError if the file already exists before we open it.
                    fd = os.open(full_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0))
                    try:
                        locks.lock(fd, locks.LOCK_EX)
                        for chunk in content.chunks():
                            os.write(fd, chunk)
                    finally:
                        locks.unlock(fd)
                        os.close(fd)
            except OSError, e:
                if e.errno == errno.EEXIST:
                    # Ooops, the file exists. We need a new file name.
                    name = self.get_available_name(name)
                    full_path = self.path(name)
                else:
                    raise
            else:
                # OK, the file save worked. Break out of the loop.
                break

        if settings.FILE_UPLOAD_PERMISSIONS is not None:
            os.chmod(full_path, settings.FILE_UPLOAD_PERMISSIONS)

        return name
代码在这个文件的158行,函数传入参数name,第二句的print语句是我自己加上的,name路径就是存入数据库的路径,full_path路径是全路径,所以调用self.path的作用不言而喻了(代码在242行)。这里不需要全路径。 再往下两个if语句9行,功能:去掉文件名(就是文件夹路径),判断是否存在,不存在创建,然后创建不成功报错。这里也需要创建文件夹目录。 再往下的while语句就是存储文件代码了(\(≧▽≦)/激动~)。第一个if语句不明白是什么意思,在前面不知道怎么有这个属性,我也没往前找,不过应该不碍事,解释中介绍说普通上传在else里面。else里面的代码我只懂for循环,那个locks,在同一目录下有locks.py,看到一堆windows接口没兴趣研究,看注释好像是“有两个线程同时对同名文件写文件,会重新获取文件名”涉及到下面的except。这里直接设置保存图片代码。 最后的if语句应该是设置文件夹的权限。 找到这个文件,开始乱找一气,从models里的save开始没找到。后来想起调试了,没有设置错的上传路径,报错“Attempted access to '\a.jpg' denied”。然后根据Traceback,找到了文件。记录下执行顺序: views里的save(),下面省略若干,到了\lib\site-packages\django\db\models\fields\files.py 249行 file.save(file.name, file, save=False), 86行 self.name = self.storage.save(name, content) 然后到了文件\lib\site-packages\django\core\files\storage.py 44行 name = self.get_available_name(name) , 70行 while self.exists(name):, 230行 return os.path.exists(self.path(name)), 没错时,在45行,转到_save函数。

Continue

今天用python进行网站数据采集,该站主要有这么几种措施防止数据采集: 1、div标签不标准。闭合标签跑太远,导致采集不准确。 2、放置干扰字符。这种直接提示错误,没有办法采集。错误提示:'ascii' codec can't encode character u'\u3009' in position 5 解决方案: 第一种如果处理不好会带有许多原站信息,采用缩小div标签的范围,但是效果不明显。感觉用正则判断比较不错,但是又经常将标签前后放置很多空格和换行,还是很麻烦。 第二种,根据提示的字符,找到对应的字符“〉”,我到原文中搜索一看,差,震惊。竟然这么写的:“<p〉”。我是没有直接替换,采用保存到文件,然后手动修改,再读取文件处理。

Continue