web2py / web2py-book Goto Github PK
View Code? Open in Web Editor NEWweb2py-book
License: Other
web2py-book
License: Other
I think that un-match line number about the description and the code.
Please see following.
Line7 -> ok
Line8 -> Line6
Line9 -> Line8
Line10 -> Line9
Line11 -> Line10
thanks.
http://www.web2py.com/books/default/chapter/29/03#An-image-blog
Notice the following statements:
db.post
table using only the specified fields.request.vars
) within the current session (the session is used to prevent double submissions, and to enforce navigation). If the submitted form variables are validated, the new comment is inserted in the db.post
table; otherwise the form is modified to include error messages (for example, if the author's email address is invalid). This is all done in line 9!.response.flash
is a web2py variable that is displayed in the views and used to notify the visitor that something happened.def index():
images = db().select(db.image.ALL, orderby=db.image.title)
return dict(images=images)
def show():
image = db.image(request.args(0,cast=int)) or redirect(URL('index'))
db.post.image_id.default = image.id
form = SQLFORM(db.post)
if form.process().accepted:
response.flash = 'your comment is posted'
comments = db(db.post.image_id==image.id).select()
return dict(image=image, comments=comments, form=form)
def download():
return response.download(request, db)
In the file sources/29-web2py-english/03.markmin in line 355 seems to be a typo. The page says:
Here is yet another better wat to create the same form:
I think it should be:
Here is yet another better way to create the same form:
Second half of Chapter 9 is totally messed-up in the online version (http://web2py.com/books/default/chapter/29/09/access-control). Everything is fine till "Renaming Auth Tables" section. The rest is pretty much unusable... This also includes the table of content.
The PDF is fine on the other hand.
Due to this: web2py/pydal#38
I think it is related to this change in web2py:
http://code.google.com/p/web2py/source/detail?r=a942e058c684987c211f13739b32f6308941f521
I updated web2py and accessing a book's index (via the menu) throws a format error in default.py line no. 101
I fixed the book error by using an int 0 by default for the chapter number instead of the "0" string:
diff --git a/controllers/default.py b/controllers/default.py
index 594eab2..c363439 100644
--- a/controllers/default.py
+++ b/controllers/default.py
@@ -94,7 +94,7 @@ def calc_date(now=request.utcnow.date()):
return now.strftime(format)
def chapter():
- book_id, chapter_id = request.args(0), request.args(1,cast=int,default='0')
+ book_id, chapter_id = request.args(0), request.args(1, cast=int, default=0)
subfolder = get_subfolder(book_id)
info = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=TIME_EXPIRE)
chapters = cache.ram('chapters_%s' % subfolder, lambda: get_chapters(subfolder), time_expire=TIME_EXPIRE)
P.139 missing word: "For example they will allow you sync your app with..."
P.139 extra letter: "..a Wizard that can help you create a new application."
P.163 2 misspelling: "For this reason they are placed into a container calle current, which is..."
P.165 jumbled words + missing word: "nor one should use it assign class attributes" should probably be: "nor should one use it to...."
P.177 double printing: "If you are storing sessions on filesystems and ..." paragraph is repeated 2x
P.189 misspelling: "provides a way to define pluralization rules for each language, as well as..."
P.202 missing words/nonsensical: "The version number of made part of the file url as in the previous example."
P.274 misspelling: ".. it is possible that some table are defined even if not needed."
P.286 superfluous word: "If as_dict is set to True, the results cursor returned by the DB driver will..."
P.296 wrong chapter ref: "They will be explained in more detail in chapter <8>" Should be chapter 7 (SQLFORM, etc)
P.315 missing word: "On relational databases they all mapped into text fields..."
P.361 missing argument name: " is a list oof INPUTs or TAGBUTTOONS..."
P.361 missing capitalization: "idden fields can be..."
P.361 superfluous word: "So you have to explicitly move hidden fields..."
P.381 missing word: "Because the record is actually updated (only its previous state..."
P.405 missing letter: "By default all the URI generated by the grid..."
P.409 missing word: "showbutton allowws to turn off all buttons."
P.411 missing letter: "There is a extra argument constraints which is a..."
P.411 missing letter: "There is a extra argument linked_tables which is a..."
P.412 missing letter: "that displays the table name and it need both the singular and..."
P.412 missing letter: "web2py normally guesses them but you can set the explicitly:..."
P.501 superfluous letter: "you can refer to the following CSS-like equivalent..."
Also, the book would be tremendously improved through a more thorough (and corrected) index. Here's some things I have found missing/corrected:
BEAUTIFY, 162, 251
datetime, 69, 276, 317
FORM, 86, 240, 346(!!)
format, 92, 275
grids, 404
Also: Misspelling: IS_EQUEL_TO (sic)
jquery, chapter 11
jquery effects, 500
lambda, 62, 276
LOAD, 184, 515
linkto, 360, 367-9
multiple validators, 387
notnull, 275 (not p.274 as listed), 277
redirect, 85, 162, 184, 353
Rows objects, 291, 302, 325
SQLFORM, 101, 356, 370
SQLFORM.grid, 290, 404
SQLFORM.smartgrid, 296, 404
unique, 277 (not 274 as listed)
validators, 162, 385, 399
WWGET, 452, 535
XML, 235, 325-6, 464
At Chapter 3:
Line 6 sets the value for the reference field, which is not part of the input form >because it is not in the list of fields specified above.
Line 7 creates an insert form SQLFORM for the db.post table using only the specified >fields.
At first there is an issue with the numbering of code lines.
Second, the phrases 'fields specified above' and 'only the specified fields' I think must be left overs from previous obsolete versions. I guess these lines should be re-written.
This line of the book is not rendered properly:
https://github.com/mdipierro/web2py-book/blob/master/sources/29-web2py-english/04.markmin#L1225
I started Polish translation of the book. I have translated the first two chapters and I'm going to continue it. I would like to push the translation (in progress) in the repo; may be anyone will join in the meantime. If I will have translating it yourself, I'm done in June. Please instruction.
Latest documentation: https://github.com/mdipierro/web2py-book/blob/d67c72d3e1cf4e7cab8849388fc5e06bc025baad/sources/29-web2py-english/07.markmin#L2503
showbutton does not exist as an option in the code. The documentation needs to be corrected or the code needs to be implemented.
This goes along with pull request 1095 (web2py/web2py#1095) on web2py source repository.
Some of the translated chapters have bad markmin (probably bad syntax mistyped when translating). I'll try to fix them and request a new source update asap.
In the 'Homemade task queues' section, the book claims that by running
python web2py.py -S app -M -R applications/app/private/myscript.py -A a b c
you get the command line arguments 'a', 'b' and 'c':
sys.args=['a','b','c']
It should say instead
sys.argv=['applications/app/private/myscript.py','a','b','c']
There is no args
in sys
.
When writing translations locally, if you want to update the rendered page, you have to erease the browser cache and also delete the static chapters.
I have modified the book controller to disable cache and using old static chapters by checking request.is_local.
The static files are created on each request. In production, the behavior should be the current (supposing request.is_local is always False).
diff --git a/controllers/default.py b/controllers/default.py
index a50245b..93f840d 100644
--- a/controllers/default.py
+++ b/controllers/default.py
@@ -2,6 +2,14 @@
import os, datetime
session.forget()
+TIME_EXPIRE = 60*60*24
+FORCE_RENDER = False
+
+# this is for checking new content instantly in development
+if request.is_local:
+ TIME_EXPIRE = -1
+ FORCE_RENDER = True
+
response.title = 'web2py'
response.subtitle = 'Full Stack Web Framework, 4th Ed.\nwritten by Massimo Di Pierro in English'
response.menu = []
@@ -74,7 +82,7 @@ def convert2html(book_id,text):
def index():
books = {}
for subfolder in FOLDERS:
- books[subfolder] = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=60*60*24)
+ books[subfolder] = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=TIME_EXPIRE)
return locals()
def calc_date(now=request.utcnow.date()):
@@ -88,14 +96,14 @@ def calc_date(now=request.utcnow.date()):
def chapter():
book_id, chapter_id = request.args(0), request.args(1,cast=int,default='0')
subfolder = get_subfolder(book_id)
- info = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=60*60*24)
- chapters = cache.ram('chapters_%s' % subfolder, lambda: get_chapters(subfolder), time_expire=60*60*24)
+ info = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=TIME_EXPIRE)
+ chapters = cache.ram('chapters_%s' % subfolder, lambda: get_chapters(subfolder), time_expire=TIME_EXPIRE)
filename = os.path.join(FOLDER,subfolder,'%.2i.markmin' % chapter_id)
dest = os.path.join(request.folder, 'static_chaps', subfolder, '%.2i.html' % chapter_id)
response.headers['Cache-Control'] = 'public, must-revalidate'
response.headers['Expires'] = calc_date()
response.headers['Pragma'] = None
- if not os.path.isfile(dest):
+ if (not os.path.isfile(dest)) or FORCE_RENDER:
content = open(filename).read()
content = convert2html(book_id,content).xml()
if not os.path.exists(os.path.dirname(dest)):
@@ -111,8 +119,8 @@ def search():
book_id = request.args(0) or redirect(URL('index'))
search = request.vars.search or redirect(URL('chapter',args=book_id))
subfolder = get_subfolder(book_id)
- info = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=60*60*24)
- chapters = cache.ram('chapters_%s' % subfolder, lambda: get_chapters(subfolder), time_expire=60*60*24)
+ info = cache.ram('info_%s' % subfolder, lambda: get_info(subfolder), time_expire=TIME_EXPIRE)
+ chapters = cache.ram('chapters_%s' % subfolder, lambda: get_chapters(subfolder), time_expire=TIME_EXPIRE)
results = []
content = H2('No results for "%s"' % search)
for chapter in chapters:
http://web2py.com/books/default/chapter/29/06#Self-Reference-and-aliases
The first example should have db.person form instead of 'reference person'.
Do you prefer pull requests?
-rif
According to Massimo:
The filenames are truncated according to the size of the uploadfield. This defaults to 512.
web2py renames the uploaded filenames as tablename+code+hash.extension
The total len(tablename+code+hash+extension)<=512
This means len(hash) <= 512 - len(tablename+code+extension)
The hash is a base64 encoded of the original filename.
If this hash exceeds 512 - len(tablename+code+extension) the file is truncated.
Note that this means that, if one's filesystem does not support filenames this long, it can generate names that will cause an error when an attempt is made to create them. By setting the upload field size as appropriate for your filesystem, this can be avoided (but now the hash of the original filename may be truncated, preventing recovery of the original filename without some other mechanism).
This information is not present in the documentation; the discussion of the Field constructor (in chapter 6) says that length
has meaning for upload
fields, but says nothing about what it is used for, and the "More on Uploads" section talks about creating a filename, but not about how or how that might be influenced (and why one might want to).
It looks like GAE supports SSL on non-appspot.com domains. That seems to conflict with what is written on the topic.
The last section of code reads:
def first():
form = SQLFORM.factory(Field('visitor_name', requires=IS_NOT_EMPTY()))
if form.process().accepted:
name = form.vars.visitor_name
redirect(URL('second',vars=dict(name=name)))
return dict(form=form)
def second():
name = request.vars.visitor_name or redirect(URL('first'))
return dict(name=name)
The request.vars.visitor_name
should be request.vars.name
at chapter 29 section 05 the-views#Default-page-layout in the unordere list:
"It displays both response.title and response.subtitle which can be set in a model. If they are not set, it adopts the application name as title"
Model should be controller.
Tested with 2.5.1-stable+timestamp.2013.06.06.15.39.19
That folder contained what was meant to be the 4th edition translation (which was never translated save a few lines, sometimes using automated online tools). The 4th edition english template files were replaced with the complete spanish translation 5th edition but I am not sure about those files should actually belong to a new folder or (as currently) replace the 4th edition files.
In case we keep the current folder, the info files (including real credits and resource versions) should be also updated to reflect the book version.
Also note that, as of now, the completed translation is marked as in-progress (while it is just a couple of months behind last updates to the 5th edition of the english book)
trivial spelling errors: http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer
One field is special: "request_tenant". This field does not exist but you can create it and add it to any of your tables (or them all):
I think should be phrased (OR ALL OF THEM)
enhancement, that prevents you from forgetting to disallow viewing of none public posts.
I think should be spelled NON-PUBLIC posts
In case you actually do want items left out by the common filter (for example, allowing the admin to see none public posts), you can either
NON-PUBLIC posts
"nonpublic" is also accepted (http://www.merriam-webster.com/thesaurus/nonpublic)
Alex Glaros
At http://web2py.com/books/default/chapter/29/13?search=Caching%20with%20Redis
the module is redis_cache not redis. Patch below:
This would be a big change, but I think it would be a lot better if the documentation was organized like the one for php. There could be more examples about each function, and these examples would be very easy to find. There are many places in the book where it's not obvious how to use a function, or how to use it in a more complex way. Php docs used to help me with these things when I was coding a lot with php.
web2py is 2.4.5-stable+timestamp.2013.03.18.22.46.22
There is a small bug.
class RadioWidget(OptionsWidget):
...
def widget(cls, field, value, **attributes):
...
checked = {'_checked': 'checked'} if k == value else {}
But 'value' is a list.
Possible fix is something like
if isinstance(value, (list,tuple)):
value = value[0]
else: value = str(value)
in the beginning of widget()
In "A simple wiki" section of chapter 3
a simple wiki
The keywords are 'page' and 'file' used in the define_table .
I am working on a web2py based application called phyloShiny.I have made a patch in biopython for the application but it does not not works in web2py though that piece of code works fine on the python shell using a test case.
Also how to test the working of a site on the local host if it requires data to be extracted from another site.
I copied the restful "more complex example" from the online book and spent hours trying to get it to work correctly. Whenever I used curl to send a post it would return "errorid". After debugging the code I realized the function was returning a row object instead of a dict. The row object does not have the length attribute so the rocket server wouldn't return the correct data. The fix is to simply have the POST routine return a dictionary:
if table_name == 'person':
return db.person.validate_and_insert(**vars)
to
if table_name == 'person':
return dict(db.person.validate_and_insert(**vars))
This problem seems to also exist with most of the restful post examples. Unless maybe it's an issue with web2py and the validate_and_insert function should return a dict instead of a row object.
These may or not be corrections, therefore I cannot make a pull request out of them:
First, the book says:
"... The files that compose a plugin are not treated by web2py any differently than other files except that admin understands from their names that they are meant to be distributed together, and it displays them in a separate page:.."
But, then, it says
"... Yet as a matter of fact, by the definition above, these plugins are more general than those recognized as such by admin. ..."
It's not clear to me what type of plugin is supposed to be more general, a web2py plugin or a common plugin
\@////contactenos
:code
That is the syntax I used for the spanish translation
MARKMIN
or MARKMIN for refering to the core helperChapter 9: accessible_query is marked as incompatible with GAE, but I think that the book should note that it is (I suppose) supported by the GAE SQL adapter.
Several lines in code examples of the english version have one "" for splitting lines, while there's need to use two "\" for proper render. I did not apply this change since I'm not sure it is the correct syntax.
Chapter 13:
This:
"... Sessions are automatically forgotten is unchanged. ..."
Should not be changed with this?
"... Sessions are automatically forgotten if unchanged. ..."
Routes of classes such as DAL, Rows, ... include .sql., which is an old notation. Why not use the new syntax, such as gluon.dal.Class?
EDIT:
line 2537
"... The grid and smartgrid gadgets are here to stay but they are marked experimental ..."
A previous blockquote near line 2287 says that since 2.0 grid and smartgrid are not experimental anymore. Both sentences are somewhat contradictory.
Chapter 6:
delete_record (although it is self-explained as some will hasten to observe) is only mentioned as unavailable option when retrieving cached Row objects. The feature is not listed anywere else.
Chapter 4:
"... private files are accessed by the controllers but not directly by the developer. ..."
Currently, the admin app allows accessing the private folder the same way as with static, models, etc. The restriction described in the book does not apply for the current version. IIRC, other sections of the book mention the private folder as invisible to the developer.
There are code comments with "# ..." or "#...". It's not clear if they should have actual comments or be removed.
I AM SORRY, THIS IS THE MISTAKE; I DON'T KNOW WHERE DELETE THIS ISSUE, PLS IGNORE IT.
I think
are improperly listed inside the block "Raw SQL" and should be moved to better position.
Hi,
Is it possible to add line numbers and syntax highlighting to code in the examples? It can be hard to follow when you refer to the code by line number but there's no line numbers for the code in example.
I see there seems to be already syntax highlighting support for different languages. There's a line # extra['code'] = lambda code: CODE(code,language='web2py').xml()
that I suppose would enable syntax highlighting for python, but it's commented out, I wonder why?
The 4th code block under HTML helpers reads like this:
{{=DIV(B(I("hello ", "<world>"
))), _class="myclass")}}
The 3rd parenthesis after <world>
is redundant and creates an error, the DIV parenthesis got already closed after _class="myclass"
In http://web2py.com/books/default/chapter/29/03#A-wiki you use line numbers to refer to parts of code cited above. Unfortunately no line number are provided and the code is 50+ lines long
I want to give a friendly suggestion to include "Next" as well as "previous" buttons (online version) for moving back and forth while reading the chapters, as it is very non-intuitive to scroll back while you are reading something and you have to change chapters for some references.
Hope you will see in this regard.
The new twitter api does not support simple http requests, so the current recipe in the book will not work. In fact, the tweets widget in the admin app had to be replaced with a js timeline for the same reason.
Now, api requests from apps need OAuth authentication, provide app special keys, etc.
Sometimes one does not want work with the following:
{{=form.custom.begin}}
Image name: <div>{{=form.custom.widget.name}}</div>
Image file: <div>{{=form.custom.widget.source}}</div>
Click here to upload: {{=form.custom.submit}}
{{=form.custom.end}}
And wants work with pure HTML and the web2py CSS convention. However, I guess is not clear that, using a custom edit form , the developer has to put in his HTML the following hidden input, besides the _formname hidden input:
<input type="hidden" value="id_value" name="id">
This informs to web2py, in an edit form, the instance id to be updated.
Besides, there are very few explanation about using of one form with multiples tables. I know that there is one (quick) section about it, but does not mention at all about the use of edit form or even this with a custom form. This idea was previously raised in this thread: https://groups.google.com/forum/#!topic/web2py/hpH7a3Qz3Wg.
I think something like above could be in the book and it will save lot of hours of beginners.
From this post
https://groups.google.com/d/msg/web2py/r17tXU9RMRw/pubp17welyIJ
Seems that plugin_wiki will be deprecated. There is still a section from the last book 12th chapter that discusses it. Also, it has an initial disclaimer saying that it is still under development, so there's no backwards compatibility guaranteed.
Maybe that disclaimer needs also a deprecation warning and a notice on the new auth.wiki
By the way. That section could be replaced with a discussion on auth.wiki illustrating the way for implementing the same features as plugin_wiki plus the new feature additions.
The solution consists of disabling migrations for all tables and enabling fake migrations:
db.define_table(....,migrate=True,fake_migrate=True)
but as I understend we need to set migrate=False in order to disabling migrations for all tables.
Am I right ?
return db(db.page.title.contains(keyword).select().aslist()
bracket lost after 'keyword'
should be:
return db(db.page.title.contains(keyword)).select().aslist()
nice project, thanks
errors can be found in ret.error.
It's ret.errors
And the nature (type, use) of ret.errors isn't described.
Self-closing tags can be generated with the TAG helper. This is useful and could be added to the book (Custom helpers, TAG; 05.markmin around line 1214), along the lines of:
To generate a self-closing tag, the tag name must end with a "/".
{{=TAG['link/'](_href='http://web2py.com')}}
generates the following XML:
<link href="http://web2py.com"/>
In subsection "Logical operators", Chapter 6 "DAL", the symbol for tilde (negation unary) is not rendered with {\ft ~} outside quoted code. I've checked that "{\ft {$\mathtt{\sim}$}}" renders the tilde properly.
Also {\char`~} works properly.
As described in: https://groups.google.com/forum/#!topic/web2py/EKz3FJc6ZPY
the example in the book never explicitly states that smartgrid requires db.comment.image_id.readable attribute to be set to True to work correctly.
In 6.17.6 the part where there is talk about the unary operator the operator character is missing within the quotes:
This is the books text:
or by explicit negation with the " " unary operator:
But it should be:
or by explicit negation with the "~" unary operator:
In deployment recipes, under GAE Datastore the "Eventual consistency" section seems to be mostly wrong.
The first paragraph seems OK, but the second paragraph claims that web2py doesn't rely on "primary Datastore keys" and that the "id" field is just a regular field assigned by web2py. Reading the code that simply isn't the case, and hasn't been at least as far back as the git repository goes (2 years). The id is the actual DB-assigned id from the entity key.
Therefore the rest of the section (which explains the consequences with an example) is just wrong. The issue only exists if one tries to retrieve the newly added row by a non-id field.
I guess the example should be altered to retrieve the newly added row by a non-id field, or minimally completely removed.
http://www.web2py.com/book/default/chapter/05#URL
leads to http://www.web2py.com/book/default/04#markmin_URL
which returns invalid function (default/04)
instead of http://www.web2py.com/books/default/chapter/29/04/the-core#URL
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.