Giter Club home page Giter Club logo

dongweiming / web_develop Goto Github PK

View Code? Open in Web Editor NEW
1.2K 86.0 534.0 837 KB

《Python Web开发实战》书中源码

Home Page: https://zhuanlan.zhihu.com/p/22371355

License: GNU General Public License v3.0

Python 57.12% Thrift 0.33% HTML 3.69% Jupyter Notebook 14.09% JavaScript 3.47% Smarty 0.02% CSS 0.29% C 13.47% SaltStack 0.34% Mako 0.01% VCL 2.09% Dockerfile 0.34% Shell 0.01% Cython 0.48% SCSS 0.11% Jinja 4.15%
python web webdevelopment flask ipython celery mq asyncio jupyter-notebook mako

web_develop's Introduction

Python Web开发实战

《Python Web开发实战》这本书的源代码项目

购买链接

  1. 京东
  2. 亚马逊
  3. China-pub
  4. 当当

重要提示

  1. 进入虚拟机请首先更新下项目代码库:

    ❯ cd web_develop
    ❯ git pull --rebase origin master
    
  2. fork的时候可以顺便点个star😂

  3. 如果使用Vagrant启动时,提示类似如下信息:

    ==> default: A newer version of the box 'dongweiming/web_develop' is available! You currently
    ==> default: have version '0.X'. The latest is version '0.Y'. Run
    ==> default: `vagrant box update` to update.
    

    那么可以使用vagrant box update更新一下。

  4. 如果下载box文件很慢,可以通过百度网盘下载,然后使用vagrant box add dongweiming/web_develop virtualbox.box初始化。

重要链接

  1. 安装设置
  2. 勘误
  3. Python社区
  4. Python之美

本书大事记

  • 2017-02-10: 本书四印3k册上市
  • 2016-11-10: 本书已经确定要输出到**了!
  • 2016-11-01: 本书三印2k册上市
  • 2016-10-10: 本书二印2k册上市
  • 2016-09-12: 本书上市,同一天首印3k册售罄
  • 2016-09-02: 开始预售
  • 2016-08-15: 写作完成
  • 2015-12-20: 开始写作

web_develop's People

Contributors

bagechashu avatar dependabot[bot] avatar dongweiming avatar mislink avatar moling3650 avatar timgates42 avatar tntc4stl3 avatar zyt312074545 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web_develop's Issues

第3章LocalProxy的用法问题

https://github.com/dongweiming/web_develop/blob/master/chapter3/section4/app_with_local_proxy.py#L19

def get_current_user():

    users = User.query.all()
    return random.choice(users)

current_user = LocalProxy(get_current_user)

在一个请求中,每次获取current_user的属性都会重新执行一次get_current_user,导致一次请求会多次查询数据库。

也就是说这样的语句

name = current_user.name
email = current_user.email

会导致查询2次数据库。

因为current_user是一个代理对象,我将上述代码简化,如下:

Python 3.5.2 (default, Jun 28 2016, 08:46:01) 
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from werkzeug.local import LocalProxy
>>> user = {}
>>> def get_current_user():
...     print("call")
...     return user
... 
>>> current_user = LocalProxy(get_current_user)
>>> current_user["name"] = "123"
call
>>> current_user["name"]
call
'123'
>>> current_user.__getitem__("name")
call
'123'
>>> 

每次获取current_user的属性都会打印出“call”,也就是执行一次get_current_user。

第3章 P34 自定义URL转换器

import urllib

from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)


class ListConverter(BaseConverter):

    def __init__(self, url_map, separator='+'):
        super(ListConverter, self).__init__(url_map)
        self.separator = urllib.unquote(separator)

    def to_python(self, value):
        return value.split(self.separator)

    def to_url(self, values):
        return self.separator.join(BaseConverter.to_url(value)
                                   for value in values)


app.url_map.converters['list'] = ListConverter


@app.route('/list1/<list:page_names>/')
def list1(page_names):
    return 'Separator: {} {}'.format('+', page_names)


@app.route('/list2/<list(separator=u"|"):page_names>/')
def list2(page_names):
    return 'Separator: {} {}'.format('|', page_names)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)

BaseConverter.to_url(value)
是否改为
BaseConverter.to_url(self,value)super(ListConverter,self).to_url(value)
因为to_url方法是一个对象方法,以下是BaseConverter的源码

class BaseConverter(object):

    """Base class for all converters."""
    regex = '[^/]+'
    weight = 100

    def __init__(self, map):
        self.map = map

    def to_python(self, value):
        return value

    def to_url(self, value):
        return url_quote(value, charset=self.map.charset)

不过flask源码的app.py文件有一段注释掉的自定义转换器示例代码,如下:

class ListConverter(BaseConverter):
    def to_python(self, value):
        return value.split(',')
    def to_url(self, values):
        return ','.join(BaseConverter.to_url(value)
                             for value in values)

里面也是没加self,是否也错了?
不过我在没修改的情况下调用url_for('list1',page_names='ab')就会出现
TypeError: unbound method to_url() must be called with BaseConverter instance as first argument (got str instance instead)
望作者解答一下

数据库部分代码瑕疵

第三章 Flask Web 开发中P66-P67页所示的例子中,缺少了一句关键的代码
users.create()
按照原书中的代码,执行后会报 r.Users 表不存在的问题。
其实在P67页“分析一下这个例子中“中第一条就有了,但是代码部分缺少了创建表的那一句

mac下 安装docker.img 之后初始化一直卡 不能成功问题

Running pre-create checks...
(default) Default Boot2Docker ISO is out-of-date, downloading the latest release...
(default) Latest release for github.com/boot2docker/boot2docker is v1.12.2
(default) Downloading /Users/benben/.docker/machine/cache/boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v1.12.2/boot2docker.iso...

^C

解决办法:
使用命令:docker-machine create -d virtualbox --virtualbox-boot2docker-url=https://github.com/boot2docker/boot2docker/releases/download/v1.12.2/boot2docker.iso default

关于VagrantFile的问题

VagrantFile里只要写上 config.vm.network "forwarded_port", guest: 80, host: 8080
然后执行 vagrant up 会出现

E:\vagrant>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'virtualbox.box'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1490248542028_26730
==> default: Destroying VM and associated drives...
F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/is_port_open.rb:21:in initialize': The requested address is not valid in its context. - connect(2) for "0.0.0.0" port 8080 (Errno::EADDRNOTAVAIL) from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/is_port_open.rb:21:in new'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/is_port_open.rb:21:in block in is_port_open?' from F:/vagrant/embedded/lib/ruby/2.2.0/timeout.rb:88:in block in timeout'
from F:/vagrant/embedded/lib/ruby/2.2.0/timeout.rb:32:in block in catch' from F:/vagrant/embedded/lib/ruby/2.2.0/timeout.rb:32:in catch'
from F:/vagrant/embedded/lib/ruby/2.2.0/timeout.rb:32:in catch' from F:/vagrant/embedded/lib/ruby/2.2.0/timeout.rb:103:in timeout'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/is_port_open.rb:19:in is_port_open?' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:248:in port_check'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:121:in []' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:121:in block in handle'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:257:in block in with_forwarded_ports' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:253:in each'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:253:in with_forwarded_ports' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:98:in handle'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:42:in block in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/environment.rb:567:in lock'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:41:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/prepare_forwarded_port_collision_params.rb:30:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/env_set.rb:19:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/provision.rb:80:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/clear_forwarded_ports.rb:15:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/set_name.rb:50:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/clean_machine_folder.rb:17:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/check_accessible.rb:18:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builder.rb:116:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in block in run' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/busy.rb:19:in busy'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in run' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/call.rb:53:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builder.rb:116:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in block in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/busy.rb:19:in busy' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/call.rb:53:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builder.rb:116:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in block in run' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/busy.rb:19:in busy'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in run' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/call.rb:53:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/box_check_outdated.rb:36:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/config_validate.rb:25:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/check_virtualbox.rb:17:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/match_mac_address.rb:19:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/discard_state.rb:15:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/import.rb:74:in import' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/import.rb:13:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/prepare_clone_snapshot.rb:17:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/prepare_clone.rb:15:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/customize.rb:40:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/check_accessible.rb:18:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builder.rb:116:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in block in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/busy.rb:19:in busy' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/call.rb:53:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/config_validate.rb:25:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/handle_box.rb:56:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:95:in block in finalize_action'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builder.rb:116:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in block in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/busy.rb:19:in busy' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builtin/call.rb:53:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/plugins/providers/virtualbox/action/check_virtualbox.rb:17:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/warden.rb:34:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/builder.rb:116:in call' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in block in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/busy.rb:19:in busy' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/action/runner.rb:66:in run'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/machine.rb:225:in action_raw' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/machine.rb:200:in block in action'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/environment.rb:567:in lock' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/machine.rb:186:in call'
from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/machine.rb:186:in action' from F:/vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/batch_action.rb:82:in block (2 levels) in run'
只要VagrantFile出现有关network的运行就会出问题,该怎么解决

win10用git bash 执行 $ vagrant up报错

Progress state: VBOX_E_FILE_ERROR
VBoxManage.exe: error: Appliance import failed
VBoxManage.exe: error: Could not create the imported medium 'C:\Users\dell\Virtu alBox VMs\web_dev_1476789817454_26795\box-disk1_1.vmdk'.
VBoxManage.exe: error: VMDK: cannot write allocated data block in 'C:\Users\dell \VirtualBox VMs\web_dev_1476789817454_26795\box-disk1_1.vmdk' (VERR_DISK_FULL)
VBoxManage.exe: error: Details: code VBOX_E_FILE_ERROR (0x80bb0004), component A pplianceWrap, interface IAppliance
VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleImportAppliance(s truct HandlerArg *)" at line 886 of file VBoxManageAppliance.cpp

怎么解决?

flask上传文件使用celery问题

worker端

#coding:utf-8
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename
import os

from flask import jsonify, send_from_directory, abort

from celery import Celery
import time
import zipfile
app = Celery('server', backend='redis://', broker='amqp://')

FlaskApp = Flask(__name__)

FlaskApp.config['UPLOAD_FOLDER'] = 'static/uploads/'
FlaskApp.config['ALLOWED_EXTENSIONS'] = set(['zip','rar'])

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in FlaskApp.config['ALLOWED_EXTENSIONS']

@app.task
def upload_async(upload_file,path):
    with FlaskApp.app_context():
        upload_file.save(path)


@FlaskApp.route('/upload', methods=['POST'])
def upload():
    n=0
    upload_files=request.files.keys()
    maxn=len(upload_files)
    for upload in upload_files:
        upload_file=request.files[upload]
        if upload_file and allowed_file(upload_file.filename):
            n+=1
            filename = secure_filename(upload_file.filename)
            #错误的地方
            upload_async.delay(upload_file,os.path.join(FlaskApp.root_path, FlaskApp.config['UPLOAD_FOLDER'], filename))
            # upload_file.save(os.path.join(FlaskApp.root_path, FlaskApp.config['UPLOAD_FOLDER'], filename))
            print 'hello, '+request.form.get('name', 'little apple')+'. success'
        else:
            print 'hello, '+request.form.get('name', 'little apple')+'. failed'

    return "%d upload success %d upload failed "%(n,maxn-n)


@app.task
def add(x, y):
    print "------>"
    time.sleep(5)
    print "<--------------"
    return x + y




@FlaskApp.route('/')
def hello_world():
    return 'hello world'

@FlaskApp.route('/register', methods=['POST'])
def register():
    print request.headers
    print request.form
    print request.form['name']
    print request.form.get('name')
    print request.form.getlist('name')
    print request.form.get('nickname', default='little apple')
    return 'welcome'



@FlaskApp.route('/download', methods=['GET','POST'])
def download():
    #filename = 'static/uploads/Tulip.jpg'
    filename = 'F:\mlp\myPytool\Tulip.jpg'
    if request.method == "GET":
        if os.path.isfile(os.path.join('upload', filename)):
            return send_from_directory('upload', filename, as_attachment=True)
        abort(404)



if __name__ == '__main__':
    FlaskApp.run(debug=True)
    app.start()

测试端

import requests
import zipfile
from server import *
from flask import Flask, request, redirect, url_for
import os
dirpath=os.getcwd()
picpath=dirpath+"/picture/"
filelist=os.listdir(picpath)
ziplist=[]
for i in filelist:
    name=i.rsplit(".",1)[0]+".zip"
    f = zipfile.ZipFile(dirpath+"/"+name,'w',zipfile.ZIP_DEFLATED)
    f.write(picpath+i)
    f.close()
    ziplist.append(dirpath+"/"+name)
files={}
for index,i in enumerate(filelist):
    name=i.rsplit(".",1)[0]+".zip"
    files["zip"+str(index)]=open(dirpath+"/"+name,"rb")

user_info = {'name': 'letian'}
r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=files)
# r=requests.post.delay("http://127.0.0.1:5000/upload", data=user_info, files=files)
print r.url
print r.text

ff=files.values()
for f in ff:
    f.close()
for file in ziplist:
    try:
        os.remove(file)
    except Exception,ex:
        print ex

print "end"

worker终端提示
File "e:\flasky\venv\lib\site-packages\werkzeug\datastructures.py", line 2617,
in getattr
return getattr(self.stream, name)
File "e:\flasky\venv\lib\site-packages\werkzeug\datastructures.py", line 2617,
in getattr
return getattr(self.stream, name)
DecodeError: maximum recursion depth exceeded

vagrant up出现错误

PS C:\Users\dell\Documents\GitHub\web_develop-master> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
There are errors in the configuration of this machine. Please fix
the following errors and try again:

SSH:

  • private_key_path file must exist: ~/.ssh/id_rsa

File provisioner:

  • File upload source file C:/Users/dell/.ssh/id_rsa.pub must exist

该如何解决

about Docker image

刚才pull了latest,足足6G,可怜我的120G硬盘😭

可以麻烦小明老师优化下吗?🐱

SSL read: error:00000000:lib(0):func(0):reason(0), errno 104

Mac上用parallels搭建的虚拟机来跑得,装的系统为Ubuntu 16.04 LTS。
跟着书中的安装步骤到了 > vagrant up 时就报错了加了sudo后还是一样,求帮忙看一下!
xxx@Parallels-Virtual-Platform:~/Downloads/web_develop$ sudo vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'dongweiming/web_develop' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
==> default: Loading metadata for box 'dongweiming/web_develop'
default: URL: https://atlas.hashicorp.com/dongweiming/web_develop
==> default: Adding box 'dongweiming/web_develop' (v0.5) for provider: virtualbox
default: Downloading: https://atlas.hashicorp.com/dongweiming/boxes/web_develop/versions/0.5/providers/virtualbox.box
==> default: Box download is resuming from prior download progress
An error occurred while downloading the remote file. The error
message, if any, is reproduced below. Please fix this error and try
again.

SSL read: error:00000000:lib(0):func(0):reason(0), errno 104

董老师有没有计划出电子版?

书对我我来说的确不多,但是这个大部头,拿来拿去的确不太方便
电子版方便查阅和携带,请问下有计划么?
谢谢

询问作者大大

第二章搭建开发环境,使用命令 vagrant up下载box总是出错,昨晚试了好多遍还是不行,原因都是超时。

今天再试着下载,结果报这个错:

URL: ["https://atlas.hashicorp.com/dongweiming/web_develop"]
Error: Couldn't resolve host 'atlas.hashicorp.com'

然后去网上搜索,找到作者大大在豆瓣的回复,看到一个百度云的资源,正在下载中。

请问这个.box文件下载后怎么使用
请问这个box只适用与ubuntu吗,我现在是mac。如果要用这个box必须先装一个ubuntu的虚拟机吗

勘误 文本错误

看起来第12章几个µs和ns被印刷成了 '框s' 。
P338上面的代码

In      : %timeit range(1000)
100000 loops, best of 3: 9.2 µs per loop

P341中间的代码

In   : %time range(10)
CPU times: user 0 ns, sys: 4 ns, total: 4 ns
Wall time: 8 µs
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

ubuntu16.04使用Celery+RabbitMQ+redis运行出错

[2017-01-24 14:30:30,628: WARNING/MainProcess] Received and deleted unknown message.  Wrong destination?!?

The full contents of the message body was: body: [[1, 3], {}, {u'errbacks': None, u'callbacks': None, u'chord': None, u'chain': None}] (41b)
{content_type:'application/x-msgpack' content_encoding:'binary'
  delivery_info:{'consumer_tag': 'None4', 'redelivered': False, 'routing_key': 'celery', 'delivery_tag': 2L, 'exchange': ''} headers={'\xe5\xca.\xdb\x00\x00\x00\x00\x00': None, 'P&5\x07\x00': None, 'T\nKB\x00\x00\x00': 'f638042a-d652-48ef-98bc-8680ee4e1d70', 'N\xfd\x17=\x00\x00': 'gen5561@yuan-CP65S', '\xcfb\xddR': 'py', '9*\xa8': None, '\xb7/b\x84\x00\x00\x00': 0, '\xe0\x0b\xfa\x89\x00\x00\x00': None, '\xdfR\xc4x\x00\x00\x00\x00\x00': [None, None], 'T3\x1d ': 'proj.tasks.add', '\xae\xbf': 'f638042a-d652-48ef-98bc-8680ee4e1d70', '\x11s\x1f\xd8\x00\x00\x00\x00': '(1, 3)', 'UL\xa1\xfc\x00\x00\x00\x00\x00\x00': '{}'}}

我是直接clone的代码,运行也出这个问题
经测试,消息代理使用rabbitmq的时候就会出现这个情况,使用redis的话没有问题,rabbitmq与celery的安装均是按照书上P253, P258, P265安装配置的,其他没有设置

第14章 431页, 关于OrderedDict 有歧义

OrderedDict是一个根据键值(keys)插入顺序排序的词典,
例子:
d = collections.OrderedDict([('a', 1), ('c', 2), ('b', 3)])
for k, v in d.items():
print(k, v)

书中误以为该词典是根据键值(keys)作排序的

勘误

书中,第三章第5节中 models.py 里的 create_by_upload_file函数,
with open(rst.path) as f:
少了打开方式

github上是
with open (rst.path, 'rb') as f:

第13章 关于正则匹配代理地址的问题

P386页说

直接解析 HTML 页面中的代理地址就好了。不需要那么严格的匹配。

然后给出了一个匹配“IP:Port”格式的正则表达式。
我看了 [https://github.com/dongweiming/web_develop/blob/master/chapter13/section1/config.py] 给出的 PROXY_SITES

    'http://cn-proxy.com',
    'http://www.xicidaili.com',
    'http://www.kuaidaili.com/free',
    'http://www.proxylists.net/?HTTP',
    # www.youdaili.net的地址随着日期不断更新
    'http://www.youdaili.net/Daili/http/4565.html',
    'http://www.youdaili.net/Daili/http/4562.html',
    'http://www.kuaidaili.com',
    'http://proxy.mimvp.com',

其中 http://cn-proxy.com 已经挂掉不能访问了;
其中 http://www.proxylists.net/?HTTPwww.youdaili.net 的代理是文本格式,能够直接按照给出的正则表达式匹配。
剩余的 www.xicidaili.comhttp://www.kuaidaili.com/freehttp://www.kuaidaili.com 给出代理的格式都是表格形式, IP 和端口并不在一起,使用提供的正则匹配不到。一种解决方案是用 bs 匹配 IP 后再获取兄弟节点的端口号:

bsObj = BeautifulSoup(html, 'html.parser')
ipList = bsObj.findAll('td', text=re.compile('[0-9]+(?:\.[0-9]+){3}'))
for each in ipList:
    ip = each.get_text()
    port = each.next_sibling.next_sibling.get_text() #因为换行的原因要取两次兄弟节点
    proxy = ip + ':' +port

最后一个 http://proxy.mimvp.com 就更扯了…端口一列直接是给出的图片…

综上:
原文的正则只可以匹配以“IP:Port”格式给出的文本,如果网站给出表格形式(IP 和端口在两个标签中)就匹配不到代理地址了。
代码中给出的部分网站不适用直接的正则匹配。

第三章的数据库建立表 多了个逗号

书中:

CREATE TABLE PasteFile (
id int(11) NOT NULL AUTO_INCREMENT,
filename varchar(5000) NOT NULL,
filehash varchar(128) NOT NULL,
filemd5 varchar(128) NOT NULL,
uploadtime datetime NOT NULL,
mimetype varchar(256) NOT NULL,
size int(11) unsigned NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY filehash (filehash),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

正确:

CREATE TABLE PasteFile (
id int(11) NOT NULL AUTO_INCREMENT,
filename varchar(5000) NOT NULL,
filehash varchar(128) NOT NULL,
filemd5 varchar(128) NOT NULL,
uploadtime datetime NOT NULL,
mimetype varchar(256) NOT NULL,
size int(11) unsigned NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY filehash (filehash)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

书中有一处用词需更正

第 14 章 Python 进阶,collections 模块。

Counter: 一个方便、快速计算的计时器工具。这里的计时器应该改为计数器

Flask-SQLAlchemy 一节的 db.drop_all() 报错

问题描述

如果先执行过P69数据库关联例子的代码,再执行P72页app_with_sqlalchemy.py的时候会报错,原因是从Address表有外键连接到User,traceback如下:

(venv) ❯ python app_with_sqlalchemy.py
Traceback (most recent call last):
  File "app_with_sqlalchemy.py", line 12, in <module>
    db.drop_all()
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 980, in drop_all
    self._execute_for_all_tables(app, bind, 'drop_all')
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 964, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3722, in drop_all
    tables=tables)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1856, in _run_visitor
    conn._run_visitor(visitorcallable, element, **kwargs)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1481, in _run_visitor
    **kwargs).traverse_single(element)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 871, in visit_metadata
    table, drop_ok=True, _is_metadata_operation=True)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 918, in visit_table
    self.connection.execute(DropTable(table))
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute
    return meth(self, multiparams, params)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection
    return connection._execute_ddl(self, multiparams, params)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 968, in _execute_ddl
    compiled
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1146, in _execute_context
    context)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
    exc_info
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
    context)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute
    cursor.execute(statement, parameters)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1217, 'Cannot delete or update a parent row: a foreign key constraint fails') [SQL: u'\nDROP TABLE users']

解决方法

添加Address model 并 import 到 app_with_sqlalchemy.py中,这里可以假定在 users.py 中加入以下代码,当然单独拿出来放到address.py里似乎更符合书里上下文的设定:

class Address(db.Model):
    __tablename__ = 'address'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email_address = db.Column(db.String(128), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User', back_populates='addresses')

    def __init__(self, email, user):
        self.email = email
        self.user = user

修改app_with_sqlalchemy.py 第四行,改为

from users import User, Address

p129重复条目

第5章 合理使用请求方法和状态码 p129
表 5.1 中 PATCH 的语义2和3是一样的

git文件目录的组织不太合理

一边看书,一边根据书上的内容看下git。但是发现一个问题,就是无法根据所看的章节快速定位到该章节代码存放于哪个目录,而且代码里面代码文件与模板文件也是分开的,找到代码还得再找到模板。例如81页的例子文件服务器,根据章节找到chapter3,但是无法判断出属于哪个section,找到section5后,再去templates目录下去找模板文件,但是模板文件又不在section3里,竟然在 r 目录下,这样文件找起来很费劲。为什么不在书上每个例子后面指明源码所在目录,然后在该目录下放置所有的文件,这样一目了然,而且还可以直接试运行。

第11页报错怎么解决?

F:\web_develop>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'dongweiming/web_develop' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
==> default: Loading metadata for box 'dongweiming/web_develop'
default: URL: https://atlas.hashicorp.com/dongweiming/web_develop
==> default: Adding box 'dongweiming/web_develop' (v0.5) for provider: virtualbox
default: Downloading: https://atlas.hashicorp.com/dongweiming/boxes/web_develop/versions/0.5/providers/virtualbox.box
default: Progress: 100% (Rate: 854k/s, Estimated time remaining: --:--:--)
The box failed to unpackage properly. Please verify that the box
file you're trying to add is not corrupted and try again. The
output from attempting to unpackage (if any):

x ./box-disk1.vmdk: Write failed
x ./box-disk2.vmdk: Write failed
x ./box.ovf: Write failed
x ./vagrant_private_key
x ./Vagrantfile
bsdtar.EXE: Error exit delayed from previous errors.

我反复安装多次都这样

window7系统,<python web 开发实践 >267页运行错误,什么原因?

(venv) E:\chapter9\section3>celery -A proj worker -l info

-------------- celery@USERCHI-MF1B2NM v4.0.2 (latentcall)
---- **** -----
--- * *** * -- Windows-7-6.1.7601-SP1 2017-01-05 17:14:05
-- * - **** ---

  • ** ---------- [config]
  • ** ---------- .> app: proj:0x2df5090
  • ** ---------- .> transport: amqp://dongwm:**@localhost:5672/web_develop
  • ** ---------- .> results: redis://localhost:6379/0
  • *** --- * --- .> concurrency: 4 (prefork)
    -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
    --- ***** -----
    -------------- [queues]
    .> celery exchange=celery(direct) key=celery

[tasks]
. proj.tasks.add
. proj.tasks.div

[2017-01-05 17:14:05,279: CRITICAL/MainProcess] Unrecoverable error: TypeError('
must be integer, not _subprocess_handle',)
Traceback (most recent call last):
File "e:\flasky\venv\lib\site-packages\celery\worker\worker.py", line 203, in
start
self.blueprint.start(self)
File "e:\flasky\venv\lib\site-packages\celery\bootsteps.py", line 119, in star
t
step.start(parent)
File "e:\flasky\venv\lib\site-packages\celery\bootsteps.py", line 370, in star
t
return self.obj.start()
File "e:\flasky\venv\lib\site-packages\celery\concurrency\base.py", line 131,
in start
self.on_start()
File "e:\flasky\venv\lib\site-packages\celery\concurrency\prefork.py", line 11
2, in on_start
**self.options)
File "e:\flasky\venv\lib\site-packages\billiard\pool.py", line 1008, in __init
__
self._create_worker_process(i)
File "e:\flasky\venv\lib\site-packages\billiard\pool.py", line 1117, in _creat
e_worker_process
w.start()
File "e:\flasky\venv\lib\site-packages\billiard\process.py", line 122, in star
t
self._popen = self._Popen(self)
File "e:\flasky\venv\lib\site-packages\billiard\context.py", line 383, in _Pop
en
return Popen(process_obj)
File "e:\flasky\venv\lib\site-packages\billiard\popen_spawn_win32.py", line 64
, in init
_winapi.CloseHandle(ht)
TypeError: must be integer, not _subprocess_handle

(venv) E:\chapter9\section3>Traceback (most recent call last):
File "", line 1, in
File "e:\flasky\venv\lib\site-packages\billiard\spawn.py", line 159, in spawn_
main
new_handle = steal_handle(parent_pid, pipe_handle)
File "e:\flasky\venv\lib\site-packages\billiard\reduction.py", line 121, in st
eal_handle
_winapi.PROCESS_DUP_HANDLE, False, source_pid)
WindowsError: [Error 87]

第3章 PasteFile类中使用 @property

您好请问用
@property def path(self): return get_file_path(self.filehash)
跟直接在init中写
self.path = get_file_path(self.filehash)
这2个用法有什么区别,第一个优势是什么,您为什么用第一种?谢谢

勘误

第二章 P17 第一行,应为 安装 pep8-naming

chapter3/section5 get_file_md5 f.read(chuck_size)报错

上传图片时,报unicodeDecodeError错误:

 File "/home/yyy/workspace/python/fileserver/webapp/app.py", line 59, in index
    paste_file = PasteFile.create_by_upload_file(uploaded_file)
  File "/home/yyy/workspace/python/fileserver/webapp/models.py", line 67, in create_by_upload_file
    filemd5 = get_file_md5(f)
  File "/home/yyy/workspace/python/fileserver/webapp/utils.py", line 17, in get_file_md5
    chunk = f.read(chunk_size)
  File "/usr/lib/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

环境:
Werkzeug (0.11.11)
Flask (0.11.1)

85页,create_by_upload_file方法上传同名文件报错

原方法:

**> def create_by_upload_file(cls, uploaded_file):

    rst = cls(uploaded_file.filename, uploaded_file.mimetype, 0)
    uploaded_file.save(rst.path)
    with open(rst.path, 'rb') as f:
        filemd5 = get_file_md5(f)
        uploaded_file = cls.get_by_md5(filemd5)
        if uploaded_file:
            os.remove(rst.path)
            return uploaded_file
    filestat = os.stat(rst.path)
    rst.size = filestat.st_size
    rst.filemd5 = filemd5
    return rst**

改为:

**> def create_by_upload_file(cls, uploaded_file):

    rst = cls(uploaded_file.filename, uploaded_file.mimetype, 0)
    uploaded_file.save(rst.path)
    with open(rst.path, 'rb') as f:
        filemd5 = get_file_md5(f)
        uploaded_file = cls.get_by_md5(filemd5)
    if uploaded_file:
        os.remove(rst.path)
        return uploaded_file
    filestat = os.stat(rst.path)
    rst.size = filestat.st_size
    rst.filemd5 = filemd5
    return rst**

删除文件时

需要关闭进程对文件的引用,因此需要调整下缩进,把删除的代码放在with语句的外面。

另:修改后发现,多次上传同一个文件(文件名相同)目录里仍然存在“同个”文件,只是文件名不同,没有达到只存储同一文件的效果,请作者查看下这个问题

求教开发平台习惯等

大神你好,刚买了您的书,目前只看到hello wold阶段

没在书里面找到开发时候使用的开发平台是什么

比如您平时用什么环境,什么工具写代码,如何提高开发效率

Vagrant启动的问题

#1 中,有读者提到了启动vagrant失败的问题。这是我在一台新的个人电脑启动的过程,大家可以参考:

➜  web_develop git:(master) vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'dongweiming/web_develop' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Loading metadata for box 'dongweiming/web_develop'
    default: URL: https://atlas.hashicorp.com/dongweiming/web_develop
==> default: Adding box 'dongweiming/web_develop' (v0.3) for provider: virtualbox
    default: Downloading: https://atlas.hashicorp.com/dongweiming/boxes/web_develop/versions/0.3/providers/virtualbox.box
==> default: Successfully added box 'dongweiming/web_develop' (v0.3) for 'virtualbox'!
==> default: Importing base box 'dongweiming/web_develop'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'dongweiming/web_develop' is up to date...
==> default: Setting the name of the VM: web_develop_default_1474106846037_42806
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 9000 (guest) => 9000 (host) (adapter 1)
    default: 3141 (guest) => 3141 (host) (adapter 1)
    default: 5000 (guest) => 5000 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: ubuntu
    default: SSH auth method: password
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Running provisioner: file...

其中default: Warning: Remote connection disconnect. Retrying...这种错是因为虚拟机还没启动完成,所以连接失败,在重试,得多等一会。

现在就可以进入了:

➜  web_develop git:(master) ✗ vagrant ssh
==> default: The machine you're attempting to SSH into is configured to use
==> default: password-based authentication. Vagrant can't script entering the
==> default: password for you. If you're prompted for a password, please enter
==> default: the same password you have configured in the Vagrantfile.
Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-24-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

48 packages can be updated.
0 updates are security updates.


Last login: Sun Jun 26 06:41:38 2016 from 10.0.2.2
[Oh My Zsh] Would you like to check for updates? [Y/n]: 

第13章 P386 使用fake_useragent.json缓存文件

P386 指出了使用 fake_useragent 时程序会访问被墙的网址获取 UA 缓存,所以如果不挂代理的话会报错:
urllib.error.URLError: <urlopen error timed out>
@dongweiming 提供了本地的缓存文件 web_develop/data/fake_useragent.json,要将此文件存储到/tmp 文件夹

在此有一点增加说明和一点勘误:
增加 Windows 平台 tmp 文件夹位置说明:
Windows 平台 tmp 文件夹位置为:C:\Users\username\AppData\Local\Temp
fake_useragent/settings.py中找到源码

DB = os.path.join(tempfile.gettempdir(), 'fake_useragent_{version}.json'.format(  # noqa
    version=__version__,
))
>>> import tempfile
>>> tempfile.gettempdir()
'C:\\Users\\username\\AppData\\Local\\Temp'

然而将缓存文件复制到正确的文件夹以后还是不能正常运行,依然没有正确 load 缓存文件而是在访问网站。
检查源码后增加 fake_useragent.json 文件名勘误:

__version__ = '0.1.2'

DB = os.path.join(tempfile.gettempdir(), 'fake_useragent_{version}.json'.format(  # noqa
    version=__version__,
))

可以看出文件名中缺少了 version
web_develop/data/fake_useragent.json 文件名应修改为 fake_useragent_0.1.2.json ,否则就算 cp 到正确路径还是不能正常读取缓存。

[勘误] P360 疑似表述错误

位置: 12章--了解 Linux 服务器运行情况--free

上下文: 纵轴上还有一行 "-/+ buffers/cache"......其中"-buffers/cache"表示已用内存...... "- buffers/cache" 表示可用内存......

我的疑惑: 加粗的两个部分( -buffers/cache ), 是指的同一个东西吗( 按照语境来看, 应该指示两个不同的东西 )

我的猜测: 根据上下文, 我觉得可能是想表述 + buffers/cache

第3章 P58 mako模板继承

<!DOCTYPE html>
<html lang="en">
<head>
    <%block name="head">
        <meta charset="UTF-8">
        <title>${ title() } - My Webpage</title>
    </%block>
</head>
<body>
    <div id="content">
        <%block name="content"/>
    </div>
    <div id="footer">
        <%block name="footer"/>
    </div>
</body>
</html>

<%def _name='title()'></%def>

<title>${ title() } - My Webpage</title>
是否改为
<title>${ self.title() } - My Webpage</title>
如果没加self,子模板继承后就算重写title()函数,使用parernt.head()时使用的还是原来的title函数,但此处例子是希望子模板改写title函数使相关内容发生改变

Vagrantfile 与书里内容不一致

书里多了三行

config.ssh.insert_key = false
config.ssh.private_key_path = ["~/.ssh/id_rsa"]
config.vm.provision "file", source: "~/.ssh/id_rsa.pub", destination: "~/.ssh/authorized_keys"

然后我把这三行加上之后在这个 repo 下 vagrant up , 会一直报 Authentication failure

vagrant reload
==> default: Attempting graceful shutdown of VM...
Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text.
[email protected]'s password:ubuntu
[email protected]'s password:ubuntu
    default: Guest communication could not be established! This is usually because
    default: SSH is not running, the authentication information was changed,
    default: or some other networking issue. Vagrant will force halt, if
    default: capable.
==> default: Forcing shutdown of VM...
==> default: Checking if box 'ubuntu/xenial64' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 9000 (guest) => 9000 (host) (adapter 1)
    default: 3141 (guest) => 3141 (host) (adapter 1)
    default: 5000 (guest) => 5000 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: ubuntu
    default: SSH auth method: password
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text.
[email protected]'s password:ubuntu
[email protected]'s password:ubuntu
    default: Warning: Authentication failure. Retrying...
Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text.
[email protected]'s password:    default: Warning: Connection timeout. Retrying...
Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text.
[email protected]'s password:ubuntu
[email protected]'s password:ubuntu
    default: Warning: Authentication failure. Retrying...
Text will be echoed in the clear. Please install the HighLine or Termios libraries to suppress echoed text.
[email protected]'s password:

请问这是什么情况?

好想骂人

我下载了最新版的 vagrant 和virtualbox,按默认安装了,之后呢?怎么安ubuntu? 怎么安装配置vagrant,请给一个详细pdf补充上

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.