|
CubicWeb BlogNews about the framework and its uses.
|
I went to the BayPIGgies meeting last thursday. The talk of this session was led by the chief software architect of RubberCan, Barnaby Bienkowski. The idea was to explain why Django turns out to be the choice a lot of startups make when building their web applications.
The fact that Django is recommended by Sunlight Foundation is important. This foundation is a non-partisan, non-profit organization based in Washington, DC that focuses on the digitization of government data and the creation of tools and Web sites to make that data easily accessible for all citizens. This is part of what is called Governement 2.0. It is a neologism for attempts to apply the social networking and integration advantages of Web 2.0 to the practice of government (see E-Governement).
It looks like the Sunlight Foundation recommends Django because it comes from the publishing industry. I am not sure what is so special about this, but I wish I could get more details on it, so please add your comments below.
Since the CubicWeb's community is still small, we are not yet recommended by such a large foundation, but we'll make more effort to talk about it and try to expand our community.
These days, geo-localization is a big deal in most applications. On that matter, what Django has to offer is GeoDjango, that recently became part of the Django core. It is integrated with the ORM and has pre-generated SQL queries, but it is not optimized. It uses PostGIS, which adds support for geographic objects to the PostgreSQL object-relational database. GeoDjango strives to make it as simple as possible to create geographic web applications, like location-based services. Some of the features it provides are:
- Extensions to Django’s ORM for the querying and manipulation of spatial data
- Editing of geometry fields inside the administration panels
- Loosely-coupled, high-level Python interfaces for GIS geometry operations and data formats.
OpenStreetMap is used for the backend. It provides geographic data for any part of the world. This is a nice feature and we should consider it for CubicWeb. What we provide so far is an interface IGeocodable with related views gmap-view, gmap-bubble, geocoding-json and gmap-legend. We do not query this data yet, we simply render them nicely in a Google Map. You can find the details on how to use it here.
Numerous web applications are not only service or data providers, they sell something. Satchmo is the Django tool to easily build online stores. It provides a shopping cart framework with checkout using different payment modules such as Authorize.net, TrustCommerce, CyberSource, PayPal, Google Checkout or Protx.
CubicWeb does not provide a component allowing to build an online store, it's not yet a domain we worked on. But I'd like to talk a bit about the cube cubicweb-shoppingcart. This cube defines shopping item and shopping cart, and enables to add items to the shopping cart. It defines type of shopping items and only those can be added to the shopping cart. Whereas Satchmo required to define categories and add items within a category, cubicweb-shoppingcart does not oblige to define categories. Creating shopping items is the only thing you need to do. That makes this component usable not only for online store. For example, we used this cube to manage Euroscipy registration fees reusing the generic schema of a "virtual" shopping cart and its related ressources (web widgets, validation hook, ...).
Pinax has a overall good satisfaction as it supports basics components for blogging, tagging, registration, notification and so on. But one point that was raised, is the difficulty of customizing Pinax components. It seems easy to write your own version of Pinax components, but to integrate them is a pain. All the components are tightly related and by customizing one, there is a big chance it will affect the other components.
This last point is a big disadvantage. Why? Well, as a developer there is always something that you need to adjust to fit your needs. So customizing components is something you will not avoid while developing your web application. And something I'd like to point about CubicWeb, is its simplicity of re-using existing components, which are independent from each others. This is as easy as Python inheritance. And with its VRegistry, selectors and application objects (see The VRegistry, selectors and application objects for more details), customization is well integrated into the framework.
Assemble cubes and functionalities is very easy as well. Let's think of an example. We have those three cubes: cubicweb-book, cubicweb-tag and cubicweb-comment. Cubicweb-book defines Book entity type. Cubicweb-tag defines Tag entities and the ability to tag other entity types. Cubicweb-comment defines Comment entity type and the ability to comment other entity types. What if we want to create an application in which we could tag and comment Book. Well, this is done with the following schema definition where we explicitly define the relations between Book, Tag and Comment entity types:
from yams.buildobjs import RelationDefinition
class comments(RelationDefinition):
subject = 'Comment'
object = 'Book'
cardinality = '1*'
composite = 'subject'
class tag(RelationDefinition):
subject = 'Tag'
object = 'Book'
cardinality = '**'
Since Logilab will be presenting CubicWeb at OSCON, we get to have a discount code giving 20% rebate on OSCON registration.
Please feel free to use this discount code while registering: os10fos.
See you there!
To avoid cluttering my database, and to ease file manipulation, I don't want
them to be stored in the database. I want to be able create File/Image entities
for some files on the server file system, where those file will be accessed to
get entities data. To do so, I've to set a custom BytesFileSystemStorage storage
for the File/Image 'data' attribute, which holds the actual file's content.
Since the function to register a custom storage needs to have a repository
instance as a first argument, we have to call it in a server startup hook. So I added it
in cubes/sytweb/hooks.py :
from os import makedirs
from os.path import join, exists
from cubicweb.server import hook
from cubicweb.server.sources import storage
class ServerStartupHook(hook.Hook):
__regid__ = 'sytweb.serverstartup'
events = ('server_startup', 'server_maintenance')
def __call__(self):
bfssdir = join(self.repo.config.appdatahome, 'bfss')
if not exists(bfssdir):
makedirs(bfssdir)
print 'created', bfssdir
storage = storages.BytesFileSystemStorage(bfssdir)
set_attribute_storage(self.repo, 'File', 'data', storage)
set_attribute_storage(self.repo, 'Image', 'data', storage)
- how we built the hook's registry identifier (_regid__): you can introduce
'namespaces' by using their python module like naming identifiers. This is
especially important for hooks where you usually want a new custom hook, not
overriding / specializing an existent one, but the concept may be used for
any application objects
- we catch two events here: "server_startup" and "server_maintenance". The first
is called on regular repository startup (eg, as a server), the other for
maintenance task such as shell or upgrade. In both cases, we need to have
the storage set, else we'll be in trouble...
- the path given to the storage is the place where a file added through the ui
(or in the database before migration) will be located
- be aware that by doing this, you can't write queries that will try to
restrict on the File and the Image data attribute anymore. Thankfully we don't usually do that
on a file's content or more generally on attributes for the Bytes type
Now, if you've already added some photos through the web ui, you'll have to
migrate existing data so that the file's content will be stored on the file-system instead
of the database. There is a migration command to do so, let's run it in the
cubicweb shell (in actual life, you'd have to put it in a migration script as we
saw last time):
$ cubicweb-ctl shell sytweb
entering the migration python shell
just type migration commands or arbitrary python code and type ENTER to execute it
type "exit" or Ctrl-D to quit the shell and resume operation
>>> storage_changed('File', 'data')
[........................]
>>> storage_changed('Image', 'data')
[........................]
That's it. Now, the files added through the web ui will have their content stored on
the file-system, and you'll also be able to import files from the file-system as
explained in the next part.
Hey, we're starting to have some nice features, let's give this new web
site a try. For instance if I have a 'photos/201005WePyrenees' containing pictures for
a particular event, I can import it to my web site by typing
$ cubicweb-ctl fsimport -F sytweb photos/201005WePyrenees/
** importing directory /home/syt/photos/201005WePyrenees
importing IMG_8314.JPG
importing IMG_8274.JPG
importing IMG_8286.JPG
importing IMG_8308.JPG
importing IMG_8304.JPG
The -F option tell that folders should be mapped, hence my photos will be
all under a Folder entity corresponding to the file-system folder.
Let's take a look at the web ui:
Nothing different, I can't see the new folder... But remember our security model!
By default, files are only accessible to authenticated users, and I'm looking at
the site as anonymous, e.g. not authenticated. If I login, I can now see:
Yeah, it's there! You can also notice that I can see some entities as well as
folders and images the anonymous users can't. It just works everywhere in
the ui since it's handled at the repository level, thanks to our security model.
Now if I click on the newly inserted folder, I can see
Great! I get my pictures in the folder. I can now give
a nicer name to this folder (provided I don't intend to import from it anymore, else already
imported photos will be reimported), change permissions, title for some
pictures, etc... Having good content is much more difficult than having a
good web site ;)
We started to see here an advanced feature of our repository: the ability
to store some parts of our data-model into a custom storage, outside the
database. There is currently only the BytesFileSystemStorage available,
but you can expect to see more coming in a near future.
Also, we can now start to feed our web-site with some nice pictures!
The site isn't perfect (far from it actually) but it's usable, and we can
start using it and improve it on the way. The Incremental Cubic Way :)
So see you next time to start tweaking the user interface!
These first two days essentially consisted in exploring the
javascript world.
Sandrine and Alain worked on the
javascript documentation tools and how they could be integrated
into our sphinx generated documentation.
They first studied pyjsdoc which unfortunately only generates
HTML. After a somewhat successful attempt to generate sphinx ReST, we
decided to use a consistent documentation format between python
modules and js modules and therefore switched to a home-made, very simple
javascript comment parser. Here's an example of what the parser understands:
/**
* .. cfunction:: myFunction(a, b, /*...*/, c, d)
*
* This function is very **well** documented and does quite
* a lot of stuff :
* - task 1
* - task 2
*
* :param a: this is the first parameter
* ...
* :return: 42
*/
function myFunction(a, b, /*...*/, c, d) {
}
The extracted ReST snippets are then concatenated and inserted
in the general documentation.
Katia, Julien and Adrien looked at the different testing tools
for javascript, with the two following goals in mind:
- low-level unit testing, as cubicweb agnostic as possible
- high-level / functional testing, we want to write navigation scenarios
and replay them
And the two winners of the exploration are:
- QUnit for pure javascript / DOM testing. Julien and Adrien
successfully managed to test a few cubicweb js functions, most
notably the loadxhtml jquery plugin.
- Windmill for higher level testing. Katia and Sylvain were able
to integrate Windmill within the CubicWeb unit testing framework.
Of course, there is still a lot of work that needs to be done. For
instance, we would like to have a test runner facility to run
QUnit-based tests on multiple platforms / browsers automatically.
Sylvain worked on property sheets and managed to implement
compiled CSS based on simple string interpolation. Of course,
compiled CSS are still HTTP cached, automatically recompiled
on debug mode, etc. On his way, he also got rid of the
external_resources file. Backward compatibility will of
course be guaranteed for a while.
Nicolas worked on CSS and vertical rythm and prepared a patch
that introduces a basic rhythm. The tedious work will be to get
every stylesheet to dance to the beat.
Logilab is once again hosting a sprint around CubicWeb - 5 days in our Paris offices.
The general focus will be around javascript & css :
- easily change the style of an application
- handling of bundles merging javascript and css
- have a clean javascript API, documented and tested
- have documentation about the css & javascript parts in the cubicweb book
This sprint is taking place from thursday the 29th of April 2010 to the 5th of may 2010 (weekend is off limits - the offices will be closed). You are more than welcome to come along and help out, contribute, or just pair program with someone. Coming only for a day, or an afternoon is fine too... Network resources will be available for those bringing laptops.
Address : 104 Boulevard Auguste-Blanqui, Paris. Ring "Logilab".
Metro : St Jacques or Corvisart (Glacière is closest, but will be closed from monday onwards)
Contact : http://www.logilab.fr/contact
Dates : 29/04/2010 to 30/04/2010 and 03/05/2010 to 05/05/2010
CubicWeb 3.8.0 went out last week, but now we have tested it, produced
a 3.8.1, it's show time!
One of the most important change is http server update to move from deadend
twisted.web2 to twisted.web. With this change comes the possibility to configure
the maximum size of POST request in the configuration file (was hard-coded to
100Mo before).
Other changes include:
- CubicWeb should now be installable through pip or easy_install.
This is still experimental, and we don't use it that much so please,
give us some feedback! Some cubes are now also "pipable" (comment, blog...),
but more will come with new releases.
- .execute() function lost its cache key argument. This is great news since
it was a pain to explain and most cubicweb users didn't know how to handle
it well (and I'm thre greatest beneficer since I won't have to explain over
and over again)
- nicer schema and workflow views
- refactored web session handling, which should now be cleaner, clearer, hence
less buggy...
- nicer skeleton generation for new cubes, cleaner __pkginfo__ (you don't have
to define both __depends__ / __depends_cubes__ or __recommends__ /
__recommends_cubes__ in the general case, and other cleanups)
Enjoy!
Aim : do the migration for N cubicweb instances hosted on a server to another with no downtime.
Prerequisites : have an explicit definition of the database host (not default or localhost). In our case, the database is hosted on another host. You are not migrating your pyro server. You are not using multisource (more documentation on that soon).
Steps :
on new machine : install your environment (pseudocode)
apt-get install cubicweb cubicweb-applications apache2
on old machine : copy your cubicweb and apache configuration to the new machine
scp /etc/cubicweb.d/ newmachine:/etc/cubicweb.d/
scp /etc/apache2/sites-available/ newmachine:/etc/apache2/sites-available/
on new machine : give new ids to pyro registration so the new instances can register
cd /etc/cubicweb.d/ ; sed -i.bck 's/^pyro-instance-id=.*$/\02/' */all-in-one.conf
on new machine : start your instances
cubicweb start
on new machine : enable sites and modules for apache and start it, test it using by modifying your /etc/host file.
change dns entry from your oldmachine to newmachine
shutdown your old machine (if it doesn't host other services or your database)
That's it.
Possible enhancements : use right from the start a pound server behind your apache, that way you can add backends and smoothily migrate by shuting down backends that pound will take into account.
As part of an effort to improve the documentation (see the cw_course version) a lot of chapters have been completed (and filled with real-world examples). Many more were updated and reorganized.
I won't list everything but here are the most important improvements:
- The publishing process
- Templates & the architecture of views
- Primary views customizations (including use of the uicfg module)
- Controllers
- Hooks & Operations
- Proper usage of the ORM
- Unit tests
- Breadcrumbs
- URL rewrite
- Using the CW javascript library
Last but not least, a whole new tutorial based on Sylvain's great
series Building my photos Web site has been included. It covers
some advanced topics such as Operations and sophisticated security
settings.
The visual style has been enhanced a bit to have better readability.
As always, patches are welcome !
picture under Creative Commons, courtesy of digitalnoise
This post will cover various topics:
- configuring security
- migrating an existing instance
- writing some unit tests
Here are the read permissions I want:
- folders, files, images and comments should have one of the following visibility rules:
- 'public', everyone can see it
- 'authenticated', only authenticated users can see it
- 'restricted', only a subset of authenticated users can see it
- managers (e.g. me) can see everything
- only authenticated users can see people
- everyone can see classifier entities (tag and zone)
Also, unless explicity specified, the visibility of an image should be the same as
the visibility of its parent folder and the visibility of a comment should be the same as the
one of the commented entity. If there is no parent entity, the default visibility is
'authenticated'.
Regarding write permissions, that's much easier:
- the anonymous user can't write
- authenticated users can only add comment
- managers will add the remaining stuff
Now, let's implement that!
Proper security in CubicWeb is done at the schema level, so you don't have to
bother with it in the views, for the users will only see what they have access to.
In the schema, you can grant access according to groups or RQL expressions (users
get access if the expression return some results). To implements the read
security defined above, groups are not enough, we'll need to use RQL expressions. Here
is the idea:
- add a visibility attribute on folder, image and comment, with a vocabulary
('public', 'authenticated', 'restricted', 'parent')
- add a may_be_read_by relation that links folder, image or comment to users,
- add hooks to propagate permission changes.
So the first thing to do is to modify the schema.py of my cube to define these
relations:
from yams.constraints import StaticVocabularyConstraint
class visibility(RelationDefinition):
subject = ('Folder', 'File', 'Image', 'Comment')
object = 'String'
constraints = [StaticVocabularyConstraint(('public', 'authenticated',
'restricted', 'parent'))]
default = 'parent'
cardinality = '11' # required
class may_be_read_by(RelationDefinition):
subject = ('Folder', 'File', 'Image', 'Comment',)
object = 'CWUser'
We can note the following points:
- we've added a new visibility attribute to folder, file, image and comment
using a RelationDefinition
- cardinality = '11' means this attribute is required. This is usually hidden
under the required argument given to the String constructor, but we can
rely on this here (same thing for StaticVocabularyConstraint, which is usually
hidden by the vocabulary argument)
- the 'parent' possible value will be used for visibility propagation
Now, we should be able to define security rules in the schema, based on these new
attribute and relation. Here is the code to add to schema.py:
from cubicweb.schema import ERQLExpression
VISIBILITY_PERMISSIONS = {
'read': ('managers',
ERQLExpression('X visibility "public"'),
ERQLExpression('X visibility "authenticated", U in_group G, G name "users"'),
ERQLExpression('X may_be_read_by U')),
'add': ('managers',),
'update': ('managers', 'owners',),
'delete': ('managers', 'owners'),
}
AUTH_ONLY_PERMISSIONS = {
'read': ('managers', 'users'),
'add': ('managers',),
'update': ('managers', 'owners',),
'delete': ('managers', 'owners'),
}
CLASSIFIERS_PERMISSIONS = {
'read': ('managers', 'users', 'guests'),
'add': ('managers',),
'update': ('managers', 'owners',),
'delete': ('managers', 'owners'),
}
from cubes.folder.schema import Folder
from cubes.file.schema import File, Image
from cubes.comment.schema import Comment
from cubes.person.schema import Person
from cubes.zone.schema import Zone
from cubes.tag.schema import Tag
Folder.__permissions__ = VISIBILITY_PERMISSIONS
File.__permissions__ = VISIBILITY_PERMISSIONS
Image.__permissions__ = VISIBILITY_PERMISSIONS
Comment.__permissions__ = VISIBILITY_PERMISSIONS.copy()
Comment.__permissions__['add'] = ('managers', 'users',)
Person.__permissions__ = AUTH_ONLY_PERMISSIONS
Zone.__permissions__ = CLASSIFIERS_PERMISSIONS
Tag.__permissions__ = CLASSIFIERS_PERMISSIONS
What's important in there:
- VISIBILITY_PERMISSIONS provides read access to an entity:
- if user is in the 'managers' group,
- or if visibility attribute's value is 'public',
- or if visibility attribute's value is 'authenticated' and user (designed by the 'U' variable in the expression) is in
the 'users' group (all authenticated users are expected to be in this group)
- or if user is linked
to the entity (the 'X' variable) through the may_be_read_by permission
- we modify permissions of the entity types we use by importing them and
modifying their __permissions__ attribute
- notice the .copy(): we only want to modify 'add' permission for Comment,
not for all entity types using VISIBILITY_PERMISSIONS!
- remaning parts of the security model is done using regular groups:
- 'users' is the group to which all authenticated users will belong
- 'guests' is the group of anonymous users
To fullfill our requirements, we have to implement:
Also, unless explicity specified, the visibility of an image should be the same as
the visibility of its parent folder and the visibility of a comment should be the same as the
one of the commented entity. If there is no parent entity, the default visibility is
'authenticated'.
This kind of 'active' rule will be done using CubicWeb's hook system. Hooks are
triggered on database event such as addition of new entity or relation.
The tricky part of the requirement is in unless explicitly specified, notably
because when the entity addition hook is executed, we don't know yet its 'parent'
entity (eg folder of an image, image commented by a comment). To handle such things,
CubicWeb provides Operation, which allow to schedule things to do at commit time.
In our case we will:
- on entity creation, schedule an operation that will set default visibility
- when a "parent" relation is added, propagate parent's visibility unless the
child already has a visibility set
Here is the code in cube's hooks.py:
from cubicweb.selectors import implements
from cubicweb.server import hook
class SetVisibilityOp(hook.Operation):
def precommit_event(self):
for eid in self.session.transaction_data.pop('pending_visibility'):
entity = self.session.entity_from_eid(eid)
if entity.visibility == 'parent':
entity.set_attributes(visibility=u'authenticated')
class SetVisibilityHook(hook.Hook):
__regid__ = 'sytweb.setvisibility'
__select__ = hook.Hook.__select__ & implements('Folder', 'File', 'Image', 'Comment')
events = ('after_add_entity',)
def __call__(self):
hook.set_operation(self._cw, 'pending_visibility', self.entity.eid,
SetVisibilityOp)
class SetParentVisibilityHook(hook.Hook):
__regid__ = 'sytweb.setparentvisibility'
__select__ = hook.Hook.__select__ & hook.match_rtype('filed_under', 'comments')
events = ('after_add_relation',)
def __call__(self):
parent = self._cw.entity_from_eid(self.eidto)
child = self._cw.entity_from_eid(self.eidfrom)
if child.visibility == 'parent':
child.set_attributes(visibility=parent.visibility)
Remarks:
- hooks are application objects, hence have selectors that should match entity or
relation type to which the hook applies. To match relation type, we use the
hook specific match_rtype selector.
- usage of set_operation: instead of adding an operation for each added entity,
set_operation allows to create a single one and to store the eids of the entities
to be processed in the session transaction data. This is a good pratice to avoid heavy
operations manipulation cost when creating a lot of entities in the same
transaction.
- the precommit_event method of the operation will be called at transaction's
commit time.
- in a hook, self._cw is the repository session, not a web request as usually
in views
- according to hook's event, you have access to different member on the hook
instance. Here:
- self.entity is the newly added entity on 'after_add_entity' events
- self.eidfrom / self.eidto are the eid of the subject / object entity on
'after_add_relation' events (you may also get the relation type using
self.rtype)
The 'parent' visibility value is used to tell "propagate using parent security"
because we want that attribute to be required, so we can't use None value else
we'll get an error before we get any chance to propagate...
Now, we also want to propagate the may_be_read_by relation. Fortunately,
CubicWeb provides some base hook classes for such things, so we only have to add
the following code to hooks.py:
# relations where the "parent" entity is the subject
S_RELS = set()
# relations where the "parent" entity is the object
O_RELS = set(('filed_under', 'comments',))
class AddEntitySecurityPropagationHook(hook.PropagateSubjectRelationHook):
"""propagate permissions when new entity are added"""
__regid__ = 'sytweb.addentity_security_propagation'
__select__ = (hook.PropagateSubjectRelationHook.__select__
& hook.match_rtype_sets(S_RELS, O_RELS))
main_rtype = 'may_be_read_by'
subject_relations = S_RELS
object_relations = O_RELS
class AddPermissionSecurityPropagationHook(hook.PropagateSubjectRelationAddHook):
__regid__ = 'sytweb.addperm_security_propagation'
__select__ = (hook.PropagateSubjectRelationAddHook.__select__
& hook.match_rtype('may_be_read_by',))
subject_relations = S_RELS
object_relations = O_RELS
class DelPermissionSecurityPropagationHook(hook.PropagateSubjectRelationDelHook):
__regid__ = 'sytweb.delperm_security_propagation'
__select__ = (hook.PropagateSubjectRelationDelHook.__select__
& hook.match_rtype('may_be_read_by',))
subject_relations = S_RELS
object_relations = O_RELS
- the AddEntitySecurityPropagationHook will propagate the relation
when filed_under or comments relations are added
- the S_RELS and O_RELS set as well as the match_rtype_sets selector are
used here so that if my cube is used by another one, it'll be able to
configure security propagation by simply adding relation to one of the two
sets.
- the two others will propagate permissions changes on parent entities to
children entities
Security is tricky. Writing some tests for it is a very good idea. You should
even write them first, as Test Driven Development recommends!
Here is a small test case that'll check the basis of our security model, in
test/unittest_sytweb.py:
from cubicweb.devtools.testlib import CubicWebTC
from cubicweb import Binary
class SecurityTC(CubicWebTC):
def test_visibility_propagation(self):
# create a user for later security checks
toto = self.create_user('toto')
# init some data using the default manager connection
req = self.request()
folder = req.create_entity('Folder',
name=u'restricted',
visibility=u'restricted')
photo1 = req.create_entity('Image',
data_name=u'photo1.jpg',
data=Binary('xxx'),
filed_under=folder)
self.commit()
photo1.clear_all_caches() # good practice, avoid request cache effects
# visibility propagation
self.assertEquals(photo1.visibility, 'restricted')
# unless explicitly specified
photo2 = req.create_entity('Image',
data_name=u'photo2.jpg',
data=Binary('xxx'),
visibility=u'public',
filed_under=folder)
self.commit()
self.assertEquals(photo2.visibility, 'public')
# test security
self.login('toto')
req = self.request()
self.assertEquals(len(req.execute('Image X')), 1) # only the public one
self.assertEquals(len(req.execute('Folder X')), 0) # restricted...
# may_be_read_by propagation
self.restore_connection()
folder.set_relations(may_be_read_by=toto)
self.commit()
photo1.clear_all_caches()
self.failUnless(photo1.may_be_read_by)
# test security with permissions
self.login('toto')
req = self.request()
self.assertEquals(len(req.execute('Image X')), 2) # now toto has access to photo2
self.assertEquals(len(req.execute('Folder X')), 1) # and to restricted folder
if __name__ == '__main__':
from logilab.common.testlib import unittest_main
unittest_main()
It is not complete, but it shows most of the things you will want to do in tests: adding some
content, creating users and connecting as them in the test, etc...
To run it type:
[syt@scorpius test]$ pytest unittest_sytweb.py
======================== unittest_sytweb.py ========================
-> creating tables [....................]
-> inserting default user and default groups.
-> storing the schema in the database [....................]
-> database for instance data initialized.
.
----------------------------------------------------------------------
Ran 1 test in 22.547s
OK
The first execution is taking time, since it creates a sqlite database for the
test instance. The second one will be much quicker:
[syt@scorpius test]$ pytest unittest_sytweb.py
======================== unittest_sytweb.py ========================
.
----------------------------------------------------------------------
Ran 1 test in 2.662s
OK
If you do some changes in your schema, you'll have to force regeneration of that
database. You do that by removing the tmpdb* files before running the test:
[syt@scorpius test]$ rm tmpdb*
BTW, pytest is a very convenient utilities to control test execution, from the logilab-common package.
Prior to those changes, Iv'e created an instance, fed it with some data, so I
don't want to create a new one, but to migrate the existing one. Let's see how to
do that.
Migration commands should be put in the cube's migration directory, in a
file named file:<X.Y.Z>_Any.py ('Any' being there mostly for historical reason).
Here I'll create a migration/0.2.0_Any.py file containing the following
instructions:
add_relation_type('may_be_read_by')
add_relation_type('visibility')
sync_schema_props_perms()
Then I update the version number in cube's __pkginfo__.py to 0.2.0. And
that's it! Those instructions will:
- update the instance's schema by adding our two new relations and update the
underlying database tables accordingly (the two first instructions)
- update schema's permissions definition (the later instruction)
To migrate my instance I simply type:
[syt@scorpius ~]$ cubicweb-ctl upgrade sytweb
I will then be asked some questions to do the migration step by step. You should say
YES when it asks if a backup of your database should be done, so you can get back
to the initial state if anything goes wrong...
This is a somewhat long post that I bet you will have to read at least twice ;)
There is a hell lot of information hidden in there... But that should start
to give you an idea of CubicWeb's power...
See you next time for part III !
- photo gallery;
- photo stored onto the fs and displayed through a web interface dynamically;
- navigation through folder (album), tags, geographical zone, people on the
picture... using facets;
- advanced security (eg not everyone can see everything). More on this later.
One note about my development environment: I wanted to use packaged version of
CubicWeb and cubes while keeping my cube in my user directory, let's say ~src/cubes.
It can be done by setting the following environment variables:
CW_CUBES_PATH=~/src/cubes
CW_MODE=user
The new cube, holding custom code for this web site, can now be created using:
cubicweb-ctl newcube --directory=~/src/cubes sytweb
Almost everything I want to represent in my web-site is somewhat already modelized in
existing cubes that I'll extend for my needs:
- folder, containing Folder entity type, which will be used as both 'album' and
a way to map file system folders. Entities are added to a given folder using the
filed_under relation.
- file, containing File and Image entity type, gallery view, and a file system
import utility.
- zone, containing the Zone entity type for hierarchical geographical
zones. Entities (including sub-zones) are added to a given zone using the
situated_in relation.
- person, containing the Person entity type plus some basic views.
- comment, providing a full commenting system allowing one to comment entity types
supporting the comments relation by adding a Comment entity.
- tag, providing a full tagging system as an easy and powerful way to classify
entities supporting the tags relation by linking the to Tag entities. This
will allow navigation into a large number of pictures.
Ok, now I'll tell my cube requires all this by editing cubes/sytweb/__pkginfo__.py:
__depends_cubes__ = {'file': '>= 1.2.0',
'folder': '>= 1.1.0',
'person': '>= 1.2.0',
'comment': '>= 1.2.0',
'tag': '>= 1.2.0',
'zone': None,
}
__depends__ = {'cubicweb': '>= 3.5.10',
}
for key,value in __depends_cubes__.items():
__depends__['cubicweb-'+key] = value
__use__ = tuple(__depends_cubes__)
Notice that you can express minimal version of the cube that should be used, None meaning whatever version available.
from yams.buildobjs import RelationDefinition
class comments(RelationDefinition):
subject = 'Comment'
object = ('File', 'Image')
cardinality = '1*'
composite = 'object'
class tags(RelationDefinition):
subject = 'Tag'
object = ('File', 'Image')
class filed_under(RelationDefinition):
subject = ('File', 'Image')
object = 'Folder'
class situated_in(RelationDefinition):
subject = 'Image'
object = 'Zone'
class displayed_on(RelationDefinition):
subject = 'Person'
object = 'Image'
This schema:
- allows to comment and tag File and Image entity types by adding the
comments and tags relations. This should be all we have to do for this
feature since the related cubes provide 'pluggable section' which are
automatically displayed in the primary view of entity types supporting the
relation.
- adds a situated_in relation definition so that image entities can be
geolocalized.
- add a new relation displayed_on relation telling who can be seen on a
picture.
This schema will probably have to evolve as time goes (for security handling at
least), but since the possibility to change and update the schema evolving
is one of CubicWeb features (and goals), we won't worry and see that later when needed.
Now that I have a schema, I want to create an instance of that new 'sytweb'
cube, so I run:
cubicweb-ctl create sytweb sytweb_instance
hint: if you get an error while the database is initialized, you can avoid having to reanswer to questions by running
cubicweb-ctl db-create sytweb_instance
This will use your already configured instance and start directly from
the database creation step, thus skipping questions asked by the 'create'
command.
Once the instance and database are fully initialized, run
cubicweb-ctl start sytweb_instance
to start the instance, check you can connect on it, etc...
We will customize the index page, see security configuration, use the Bytes FileSystem Storage... Lots of cool stuff remaining :)
Next post : security, testing and migration
|