proteus-4.6.1/ 0000755 0001750 0001750 00000000000 13246073656 012547 5 ustar ced ced 0000000 0000000 proteus-4.6.1/setup.py 0000644 0001750 0001750 00000005627 13235121233 014252 0 ustar ced ced 0000000 0000000 #!/usr/bin/env python
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from setuptools import setup, find_packages
import os
import re
import io
def read(fname):
return io.open(
os.path.join(os.path.dirname(__file__), fname),
'r', encoding='utf-8').read()
def get_version():
init = read(os.path.join('proteus', '__init__.py'))
return re.search('__version__ = "([0-9.]*)"', init).group(1)
def get_require_version(name):
if minor_version % 2:
require = '%s >= %s.%s.dev0, < %s.%s'
else:
require = '%s >= %s.%s, < %s.%s'
require %= (name, major_version, minor_version,
major_version, minor_version + 1)
return require
name = 'proteus'
version = get_version()
major_version, minor_version, _ = version.split('.', 2)
major_version = int(major_version)
minor_version = int(minor_version)
download_url = 'http://downloads.tryton.org/%s.%s/' % (
major_version, minor_version)
if minor_version % 2:
version = '%s.%s.dev0' % (major_version, minor_version)
download_url = 'hg+http://hg.tryton.org/%s#egg=%s-%s' % (
name, name, version)
dependency_links = []
if minor_version % 2:
# Add development index for testing with trytond
dependency_links.append('https://trydevpi.tryton.org/')
setup(name=name,
version=version,
description='Library to access Tryton server as a client',
long_description=read('README'),
author='Tryton',
author_email='issue_tracker@tryton.org',
url='http://www.tryton.org/',
download_url=download_url,
keywords='tryton library cli',
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Framework :: Tryton',
'Intended Audience :: Developers',
'Intended Audience :: Financial and Insurance Industry',
'Intended Audience :: Legal Industry',
'License :: OSI Approved :: '
'GNU Library or Lesser General Public License (LGPL)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Office/Business',
],
platforms='any',
license='LGPL-3',
install_requires=[
"python-dateutil",
],
extras_require={
'trytond': [get_require_version('trytond')],
'cdecimal': ['cdecimal'],
},
dependency_links=dependency_links,
zip_safe=True,
test_suite='proteus.tests',
tests_require=[get_require_version('trytond'),
get_require_version('trytond_party')],
use_2to3=True,
)
proteus-4.6.1/MANIFEST.in 0000644 0001750 0001750 00000000123 13175640537 014300 0 ustar ced ced 0000000 0000000 include LICENSE
include COPYRIGHT
include README
include INSTALL
include CHANGELOG
proteus-4.6.1/proteus.egg-info/ 0000755 0001750 0001750 00000000000 13246073656 015742 5 ustar ced ced 0000000 0000000 proteus-4.6.1/proteus.egg-info/top_level.txt 0000644 0001750 0001750 00000000010 13246073656 020463 0 ustar ced ced 0000000 0000000 proteus
proteus-4.6.1/proteus.egg-info/PKG-INFO 0000644 0001750 0001750 00000013424 13246073656 017043 0 ustar ced ced 0000000 0000000 Metadata-Version: 1.1
Name: proteus
Version: 4.6.1
Summary: Library to access Tryton server as a client
Home-page: http://www.tryton.org/
Author: Tryton
Author-email: issue_tracker@tryton.org
License: LGPL-3
Download-URL: http://downloads.tryton.org/4.6/
Description-Content-Type: UNKNOWN
Description: proteus
=======
A library to access Tryton's models like a client.
Installing
----------
See INSTALL
Example of usage
----------------
>>> from proteus import config, Model, Wizard, Report
Configuration
~~~~~~~~~~~~~
Configuration to connect to a sqlite memory database using trytond as module.
>>> config = config.set_trytond('sqlite:///:memory:')
Installing a module
~~~~~~~~~~~~~~~~~~~
Find the module, call the activate button and run the upgrade wizard.
>>> Module = Model.get('ir.module')
>>> party_module, = Module.find([('name', '=', 'party')])
>>> party_module.click('activate')
>>> Wizard('ir.module.activate_upgrade').execute('upgrade')
Creating a party
~~~~~~~~~~~~~~~~
First instanciate a new Party:
>>> Party = Model.get('party.party')
>>> party = Party()
>>> party.id < 0
True
Fill the fields:
>>> party.name = 'ham'
Save the instance into the server:
>>> party.save()
>>> party.name
u'ham'
>>> party.id > 0
True
Setting the language of the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The language on party is a `Many2One` relation field. So it requires to get a
`Model` instance as value.
>>> Lang = Model.get('ir.lang')
>>> en, = Lang.find([('code', '=', 'en')])
>>> party.lang = en
>>> party.save()
>>> party.lang.code
u'en'
Creating an address for the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Addresses are store on party with a `One2Many` field. So the new address just
needs to be appended to the list `addresses`.
>>> address = party.addresses.new(zip='42')
>>> party.save()
>>> party.addresses #doctest: +ELLIPSIS
[proteus.Model.get('party.address')(...)]
Adding category to the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Categories are linked to party with a `Many2Many` field.
So first create a category
>>> Category = Model.get('party.category')
>>> category = Category()
>>> category.name = 'spam'
>>> category.save()
Append it to categories of the party
>>> party.categories.append(category)
>>> party.save()
>>> party.categories #doctest: +ELLIPSIS
[proteus.Model.get('party.category')(...)]
Print party label
~~~~~~~~~~~~~~~~~
There is a label report on `Party`.
>>> label = Report('party.label')
The report is executed with a list of records and some extra data.
>>> type_, data, print_, name = label.execute([party], {})
Sorting addresses and register order
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Addresses are ordered by sequence which means they can be stored following a
specific order. The `set_sequence` method stores the current order.
>>> address = party.addresses.new(zip='69')
>>> party.save()
>>> address = party.addresses.new(zip='23')
>>> party.save()
Now changing the order.
>>> reversed_addresses = list(reversed(party.addresses))
>>> while party.addresses:
... _ = party.addresses.pop()
>>> party.addresses.extend(reversed_addresses)
>>> party.addresses.set_sequence()
>>> party.save()
>>> party.addresses == reversed_addresses
True
Support
-------
If you encounter any problems with Tryton, please don't hesitate to ask
questions on the Tryton bug tracker, mailing list, wiki or IRC channel:
http://bugs.tryton.org/
http://groups.tryton.org/
http://wiki.tryton.org/
irc://irc.freenode.net/tryton
License
-------
See LICENSE
Copyright
---------
See COPYRIGHT
For more information please visit the Tryton web site:
http://www.tryton.org/
Keywords: tryton library cli
Platform: any
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Plugins
Classifier: Framework :: Tryton
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Legal Industry
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Office/Business
proteus-4.6.1/proteus.egg-info/zip-safe 0000644 0001750 0001750 00000000001 13246073656 017372 0 ustar ced ced 0000000 0000000
proteus-4.6.1/proteus.egg-info/SOURCES.txt 0000644 0001750 0001750 00000001010 13246073656 017616 0 ustar ced ced 0000000 0000000 .drone.yml
.hgtags
CHANGELOG
COPYRIGHT
INSTALL
LICENSE
MANIFEST.in
README
setup.py
tox.ini
proteus/__init__.py
proteus/config.py
proteus/pyson.py
proteus.egg-info/PKG-INFO
proteus.egg-info/SOURCES.txt
proteus.egg-info/dependency_links.txt
proteus.egg-info/requires.txt
proteus.egg-info/top_level.txt
proteus.egg-info/zip-safe
proteus/tests/__init__.py
proteus/tests/common.py
proteus/tests/test_config.py
proteus/tests/test_context.py
proteus/tests/test_model.py
proteus/tests/test_report.py
proteus/tests/test_wizard.py proteus-4.6.1/proteus.egg-info/dependency_links.txt 0000644 0001750 0001750 00000000001 13246073656 022010 0 ustar ced ced 0000000 0000000
proteus-4.6.1/proteus.egg-info/requires.txt 0000644 0001750 0001750 00000000102 13246073656 020333 0 ustar ced ced 0000000 0000000 python-dateutil
[cdecimal]
cdecimal
[trytond]
trytond<4.7,>=4.6
proteus-4.6.1/PKG-INFO 0000644 0001750 0001750 00000013424 13246073656 013650 0 ustar ced ced 0000000 0000000 Metadata-Version: 1.1
Name: proteus
Version: 4.6.1
Summary: Library to access Tryton server as a client
Home-page: http://www.tryton.org/
Author: Tryton
Author-email: issue_tracker@tryton.org
License: LGPL-3
Download-URL: http://downloads.tryton.org/4.6/
Description-Content-Type: UNKNOWN
Description: proteus
=======
A library to access Tryton's models like a client.
Installing
----------
See INSTALL
Example of usage
----------------
>>> from proteus import config, Model, Wizard, Report
Configuration
~~~~~~~~~~~~~
Configuration to connect to a sqlite memory database using trytond as module.
>>> config = config.set_trytond('sqlite:///:memory:')
Installing a module
~~~~~~~~~~~~~~~~~~~
Find the module, call the activate button and run the upgrade wizard.
>>> Module = Model.get('ir.module')
>>> party_module, = Module.find([('name', '=', 'party')])
>>> party_module.click('activate')
>>> Wizard('ir.module.activate_upgrade').execute('upgrade')
Creating a party
~~~~~~~~~~~~~~~~
First instanciate a new Party:
>>> Party = Model.get('party.party')
>>> party = Party()
>>> party.id < 0
True
Fill the fields:
>>> party.name = 'ham'
Save the instance into the server:
>>> party.save()
>>> party.name
u'ham'
>>> party.id > 0
True
Setting the language of the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The language on party is a `Many2One` relation field. So it requires to get a
`Model` instance as value.
>>> Lang = Model.get('ir.lang')
>>> en, = Lang.find([('code', '=', 'en')])
>>> party.lang = en
>>> party.save()
>>> party.lang.code
u'en'
Creating an address for the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Addresses are store on party with a `One2Many` field. So the new address just
needs to be appended to the list `addresses`.
>>> address = party.addresses.new(zip='42')
>>> party.save()
>>> party.addresses #doctest: +ELLIPSIS
[proteus.Model.get('party.address')(...)]
Adding category to the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Categories are linked to party with a `Many2Many` field.
So first create a category
>>> Category = Model.get('party.category')
>>> category = Category()
>>> category.name = 'spam'
>>> category.save()
Append it to categories of the party
>>> party.categories.append(category)
>>> party.save()
>>> party.categories #doctest: +ELLIPSIS
[proteus.Model.get('party.category')(...)]
Print party label
~~~~~~~~~~~~~~~~~
There is a label report on `Party`.
>>> label = Report('party.label')
The report is executed with a list of records and some extra data.
>>> type_, data, print_, name = label.execute([party], {})
Sorting addresses and register order
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Addresses are ordered by sequence which means they can be stored following a
specific order. The `set_sequence` method stores the current order.
>>> address = party.addresses.new(zip='69')
>>> party.save()
>>> address = party.addresses.new(zip='23')
>>> party.save()
Now changing the order.
>>> reversed_addresses = list(reversed(party.addresses))
>>> while party.addresses:
... _ = party.addresses.pop()
>>> party.addresses.extend(reversed_addresses)
>>> party.addresses.set_sequence()
>>> party.save()
>>> party.addresses == reversed_addresses
True
Support
-------
If you encounter any problems with Tryton, please don't hesitate to ask
questions on the Tryton bug tracker, mailing list, wiki or IRC channel:
http://bugs.tryton.org/
http://groups.tryton.org/
http://wiki.tryton.org/
irc://irc.freenode.net/tryton
License
-------
See LICENSE
Copyright
---------
See COPYRIGHT
For more information please visit the Tryton web site:
http://www.tryton.org/
Keywords: tryton library cli
Platform: any
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Plugins
Classifier: Framework :: Tryton
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Legal Industry
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Office/Business
proteus-4.6.1/CHANGELOG 0000644 0001750 0001750 00000003756 13246073655 013773 0 ustar ced ced 0000000 0000000 Version 4.6.1 - 2018-03-01
* Bug fixes (see mercurial logs for details)
Version 4.6.0 - 2017-10-30
* Bug fixes (see mercurial logs for details)
* Add set_sequence method to ModelList
* Add __int__ to Model
* Allow to use keyword arguments with trytond configuration
Version 4.4.0 - 2017-05-01
* Bug fixes (see mercurial logs for details)
Version 4.2.0 - 2016-11-28
* Bug fixes (see mercurial logs for details)
* Fill default Report data
Version 4.0.0 - 2016-05-02
* Bug fixes (see mercurial logs for details)
* Add Python3 support
Version 3.8.0 - 2015-11-02
* Bug fixes (see mercurial logs for details)
* Add StateAction support to Wizard
Version 3.6.0 - 2015-04-20
* Bug fixes (see mercurial logs for details)
* Add support for PyPy
* Allow to provide extra keyword arguments to set_xmlrpc()
* Add support of fields.TimeDelta
* Remove password on set_trytond
* Manage reload, save, delete, duplicate and click as class and instance method
Version 3.4.0 - 2014-10-20
* Bug fixes (see mercurial logs for details)
* New configuration syntax
* Add Report
* Explicitly set value of parent field
* Add duplicate method
Version 3.2.0 - 2014-04-21
* Bug fixes (see mercurial logs for details)
* Models cache depends also on user
* Drop support of Python 2.6
* Allow to pass field values to new method
* Add click method for buttons
Version 3.0.0 - 2013-10-21
* Bug fixes (see mercurial logs for details)
Version 2.8.0 - 2013-04-22
* Bug fixes (see mercurial logs for details)
* Add support of fields.Dict
Version 2.6.0 - 2012-10-22
* Bug fixes (see mercurial logs for details)
Version 2.4.0 - 2012-04-23
* Bug fixes (see mercurial logs for details)
* Use loading attribute
* Add support of _buttons
* Add support of fields.Time
Version 2.2.0 - 2011-10-25
* Bug fixes (see mercurial logs for details)
* Change license to LGPL-3
* Drop support of Python 2.5
Version 2.0.0 - 2011-04-28
* Bug fixes (see mercurial logs for details)
* Manage default values of trytond configuration
Version 1.8.0 - 2010-12-24
* Initial release
proteus-4.6.1/LICENSE 0000644 0001750 0001750 00000123444 13175640537 013563 0 ustar ced ced 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
proteus-4.6.1/.hgtags 0000644 0001750 0001750 00000001360 13246073656 014025 0 ustar ced ced 0000000 0000000 3974f546b848d4ac59551db9f733d8ed62946dfd 1.8.0
c8fdae3b2338b744fce709572958884a95de87b3 2.0.0
120d0435125cf3a3c28280321962571924ad422f 2.2.0
ef9846cb18afe62182de446d8e4fa7b8393f7168 2.4.0
648c43939fd698988bde5b54f7a1dff9d47922af 2.6.0
5625ce03643f9f2b69659907754e5b0e924c689f 2.8.0
31740f7e08a0c449ce6715e1ef15392fb6326ce9 3.0.0
40affcdda4629de37997d0e5c7d3fe9ca2806b12 3.2.0
61013c4482fc95a61d2a15a8b21574a706755b10 3.4.0
2a2503ebd25887ff3668d470809c00c5bcf2c6c7 3.6.0
1e741a18e2a1f29fcc66e9ab4878554a4e63a355 3.8.0
403f21dd1bb7059a0928c46c8b21a97c14f9c720 4.0.0
d5b1e8f047748526d9a2cd354da0e86d617ec4c7 4.2.0
365af7e74c2baae38e96bc0afb1deae2d2b44ac0 4.4.0
cd4731fb373698d480a625a286de776a0b9bdc6e 4.6.0
a619bdc53ae509a3bbe9386bfde8fbf8ec16fa9c 4.6.1
proteus-4.6.1/proteus/ 0000755 0001750 0001750 00000000000 13246073656 014250 5 ustar ced ced 0000000 0000000 proteus-4.6.1/proteus/__init__.py 0000644 0001750 0001750 00000126251 13235121233 016347 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
'''
A library to access Tryton's models like a client.
'''
import sys
try:
import cdecimal
# Use cdecimal globally
if 'decimal' not in sys.modules:
sys.modules['decimal'] = cdecimal
except ImportError:
import decimal
sys.modules['cdecimal'] = decimal
import threading
import datetime
import functools
from decimal import Decimal
import proteus.config
__version__ = "4.6.1"
__all__ = ['Model', 'Wizard', 'Report']
_MODELS = threading.local()
class _EvalEnvironment(dict):
'Dictionary for evaluation'
def __init__(self, parent, eval_type='eval'):
super(_EvalEnvironment, self).__init__()
self.parent = parent
assert eval_type in ('eval', 'on_change')
self.eval_type = eval_type
def __getitem__(self, item):
if item == '_parent_' + self.parent._parent_name \
and self.parent._parent:
return _EvalEnvironment(self.parent._parent,
eval_type=self.eval_type)
if self.eval_type == 'eval':
return self.parent._get_eval()[item]
else:
return self.parent._get_on_change_values(fields=[item])[item]
def __getattr__(self, item):
try:
return self.__getitem__(item)
except KeyError:
raise AttributeError(item)
def get(self, item, default=None):
try:
return self.__getitem__(item)
except KeyError:
pass
return super(_EvalEnvironment, self).get(item, default)
def __nonzero__(self):
return True
def __str__(self):
return str(self.parent)
__repr__ = __str__
def __contains__(self, item):
if item == '_parent_' + self.parent._parent_name \
and self.parent._parent:
return True
if self.eval_type == 'eval':
return item in self.parent._get_eval()
else:
return item in self.parent._fields
class dualmethod(object):
"""Descriptor implementing combination of class and instance method
When called on an instance, the class is passed as the first argument and a
list with the instance as the second.
When called on a class, the class itself is passed as the first argument.
>>> class Example(object):
... @dualmethod
... def method(cls, instances):
... print len(instances)
...
>>> Example.method([Example()])
1
>>> Example().method()
1
"""
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
@functools.wraps(self.func)
def newfunc(*args, **kwargs):
if instance:
return self.func(owner, [instance], *args, **kwargs)
else:
return self.func(owner, *args, **kwargs)
return newfunc
class FieldDescriptor(object):
default = None
def __init__(self, name, definition):
super(FieldDescriptor, self).__init__()
self.name = name
self.definition = definition
self.__doc__ = definition['string']
def __get__(self, instance, owner):
if instance.id > 0:
instance._read(self.name)
return instance._values.get(self.name, self.default)
def __set__(self, instance, value):
if instance.id > 0:
instance._read(self.name)
previous = getattr(instance, self.name)
instance._values[self.name] = value
if previous != getattr(instance, self.name):
instance._changed.add(self.name)
instance._on_change([self.name])
if instance._parent:
instance._parent._changed.add(instance._parent_field_name)
instance._parent._on_change([instance._parent_field_name])
class BooleanDescriptor(FieldDescriptor):
default = False
def __set__(self, instance, value):
assert isinstance(value, bool)
super(BooleanDescriptor, self).__set__(instance, value)
class CharDescriptor(FieldDescriptor):
default = None
def __set__(self, instance, value):
assert isinstance(value, basestring) or value is None
super(CharDescriptor, self).__set__(instance, value or '')
class BinaryDescriptor(FieldDescriptor):
default = None
def __set__(self, instance, value):
assert isinstance(value, (bytes, bytearray)) or value is None
super(BinaryDescriptor, self).__set__(instance, value)
class IntegerDescriptor(FieldDescriptor):
def __set__(self, instance, value):
assert isinstance(value, (int, long, type(None)))
super(IntegerDescriptor, self).__set__(instance, value)
class FloatDescriptor(FieldDescriptor):
def __set__(self, instance, value):
assert isinstance(value, (int, long, float, Decimal, type(None)))
if value is not None:
value = float(value)
super(FloatDescriptor, self).__set__(instance, value)
class NumericDescriptor(FieldDescriptor):
def __set__(self, instance, value):
assert isinstance(value, (type(None), Decimal))
# TODO add digits validation
super(NumericDescriptor, self).__set__(instance, value)
class ReferenceDescriptor(FieldDescriptor):
def __get__(self, instance, owner):
value = super(ReferenceDescriptor, self).__get__(instance, owner)
if isinstance(value, basestring):
model_name, id = value.split(',', 1)
if model_name:
relation = Model.get(model_name, instance._config)
value = relation(int(id))
instance._values[self.name] = value
return value
def __set__(self, instance, value):
assert isinstance(value, (Model, type(None), basestring))
if isinstance(value, basestring):
assert value.startswith(',')
elif isinstance(value, Model):
assert value._config == instance._config
super(ReferenceDescriptor, self).__set__(instance, value)
class DateDescriptor(FieldDescriptor):
def __get__(self, instance, owner):
value = super(DateDescriptor, self).__get__(instance, owner)
if isinstance(value, datetime.datetime):
value = value.date()
instance._values[self.name] = value
return value
def __set__(self, instance, value):
assert isinstance(value, datetime.date) or value is None
super(DateDescriptor, self).__set__(instance, value)
class DateTimeDescriptor(FieldDescriptor):
def __set__(self, instance, value):
assert isinstance(value, datetime.datetime) or value is None
super(DateTimeDescriptor, self).__set__(instance, value)
class TimeDescriptor(FieldDescriptor):
def __set__(self, instance, value):
assert isinstance(value, datetime.time) or value is None
super(TimeDescriptor, self).__set__(instance, value)
class TimeDeltaDescriptor(FieldDescriptor):
def __set__(self, instance, value):
assert isinstance(value, datetime.timedelta) or value is None
super(TimeDeltaDescriptor, self).__set__(instance, value)
class DictDescriptor(FieldDescriptor):
def __get__(self, instance, owner):
value = super(DictDescriptor, self).__get__(instance, owner)
if value:
value = value.copy()
return value
def __set__(self, instance, value):
assert isinstance(value, dict) or value is None
super(DictDescriptor, self).__set__(instance, value)
class Many2OneDescriptor(FieldDescriptor):
def __get__(self, instance, owner):
relation = Model.get(self.definition['relation'], instance._config)
value = super(Many2OneDescriptor, self).__get__(instance, owner)
if isinstance(value, (int, long)):
value = relation(value)
if self.name in instance._values:
instance._values[self.name] = value
return value
def __set__(self, instance, value):
assert isinstance(value, (Model, type(None)))
if value:
assert value._config == instance._config
super(Many2OneDescriptor, self).__set__(instance, value)
class One2OneDescriptor(Many2OneDescriptor):
pass
class One2ManyDescriptor(FieldDescriptor):
default = []
def __get__(self, instance, owner):
from .pyson import PYSONDecoder
relation = Model.get(self.definition['relation'], instance._config)
value = super(One2ManyDescriptor, self).__get__(instance, owner)
if not isinstance(value, ModelList):
ctx = instance._context.copy() if instance._context else {}
if self.definition.get('context'):
decoder = PYSONDecoder(_EvalEnvironment(instance))
ctx.update(decoder.decode(self.definition.get('context')))
with instance._config.set_context(ctx):
value = ModelList(self.definition, (relation(id)
for id in value or []), instance, self.name)
instance._values[self.name] = value
return value
def __set__(self, instance, value):
raise AttributeError
class Many2ManyDescriptor(One2ManyDescriptor):
pass
class ValueDescriptor(object):
def __init__(self, name, definition):
super(ValueDescriptor, self).__init__()
self.name = name
self.definition = definition
def __get__(self, instance, owner):
return getattr(instance, self.name)
class ReferenceValueDescriptor(ValueDescriptor):
def __get__(self, instance, owner):
value = super(ReferenceValueDescriptor, self).__get__(instance, owner)
if isinstance(value, Model):
value = '%s,%s' % (value.__class__.__name__, value.id)
return value or None
class Many2OneValueDescriptor(ValueDescriptor):
def __get__(self, instance, owner):
value = super(Many2OneValueDescriptor, self).__get__(instance, owner)
return value and value.id or None
class One2OneValueDescriptor(Many2OneValueDescriptor):
pass
class One2ManyValueDescriptor(ValueDescriptor):
def __get__(self, instance, owner):
value = []
value_list = getattr(instance, self.name)
parent_name = self.definition.get('relation_field', '')
to_add = []
to_create = []
to_write = []
for record in value_list:
if record.id >= 0:
values = record._get_values(fields=record._changed)
values.pop(parent_name, None)
if record._changed and values:
to_write.extend(([record.id], values))
to_add.append(record.id)
else:
values = record._get_values()
values.pop(parent_name, None)
to_create.append(values)
if to_add:
value.append(('add', to_add))
if to_create:
value.append(('create', to_create))
if to_write:
value.append(('write',) + tuple(to_write))
if value_list.record_removed:
value.append(('remove', [x.id for x in value_list.record_removed]))
if value_list.record_deleted:
value.append(('delete', [x.id for x in value_list.record_deleted]))
return value
class Many2ManyValueDescriptor(One2ManyValueDescriptor):
pass
class EvalDescriptor(object):
def __init__(self, name, definition):
super(EvalDescriptor, self).__init__()
self.name = name
self.definition = definition
def __get__(self, instance, owner):
return getattr(instance, self.name)
class ReferenceEvalDescriptor(EvalDescriptor):
def __get__(self, instance, owner):
value = super(ReferenceEvalDescriptor, self).__get__(instance, owner)
if isinstance(value, Model):
value = '%s,%s' % (value.__class__.__name__, value.id)
return value or None
class Many2OneEvalDescriptor(EvalDescriptor):
def __get__(self, instance, owner):
value = super(Many2OneEvalDescriptor, self).__get__(instance, owner)
if value:
return value.id
return None
class One2OneEvalDescriptor(Many2OneEvalDescriptor):
pass
class One2ManyEvalDescriptor(EvalDescriptor):
def __get__(self, instance, owner):
# Directly use _values to prevent infinite recursion with
# One2ManyDescriptor which could evaluate this field to decode the
# context
value = instance._values.get(self.name, [])
if isinstance(value, ModelList):
return [x.id for x in value]
else:
return value
class Many2ManyEvalDescriptor(One2ManyEvalDescriptor):
pass
class MetaModelFactory(object):
descriptors = {
'boolean': BooleanDescriptor,
'char': CharDescriptor,
'text': CharDescriptor,
'binary': BinaryDescriptor,
'selection': CharDescriptor, # TODO implement its own descriptor
'integer': IntegerDescriptor,
'biginteger': IntegerDescriptor,
'float': FloatDescriptor,
'numeric': NumericDescriptor,
'reference': ReferenceDescriptor,
'date': DateDescriptor,
'datetime': DateTimeDescriptor,
'timestamp': DateTimeDescriptor,
'time': TimeDescriptor,
'timedelta': TimeDeltaDescriptor,
'dict': DictDescriptor,
'many2one': Many2OneDescriptor,
'one2many': One2ManyDescriptor,
'many2many': Many2ManyDescriptor,
'one2one': One2OneDescriptor,
}
value_descriptors = {
'reference': ReferenceValueDescriptor,
'many2one': Many2OneValueDescriptor,
'one2many': One2ManyValueDescriptor,
'many2many': Many2ManyValueDescriptor,
'one2one': One2OneValueDescriptor,
}
eval_descriptors = {
'reference': ReferenceEvalDescriptor,
'many2one': Many2OneEvalDescriptor,
'one2many': One2ManyEvalDescriptor,
'many2many': Many2ManyEvalDescriptor,
'one2one': One2OneEvalDescriptor,
}
def __init__(self, model_name, config=None):
super(MetaModelFactory, self).__init__()
self.model_name = model_name
self.config = config or proteus.config.get_config()
def __call__(self):
models_key = 'c%su%s' % (id(self.config), self.config.user)
if not hasattr(_MODELS, models_key):
setattr(_MODELS, models_key, {})
class MetaModel(type):
'Meta class for Model'
def __new__(mcs, name, bases, dict):
if self.model_name in getattr(_MODELS, models_key):
return getattr(_MODELS, models_key)[self.model_name]
proxy = self.config.get_proxy(self.model_name)
context = self.config.context
name = self.model_name
dict['_proxy'] = proxy
dict['_config'] = self.config
dict['_fields'] = proxy.fields_get(None, context)
for field_name, definition in dict['_fields'].iteritems():
if field_name == 'id':
continue
Descriptor = self.descriptors.get(definition['type'],
FieldDescriptor)
dict[field_name] = Descriptor(field_name, definition)
VDescriptor = self.value_descriptors.get(
definition['type'], ValueDescriptor)
dict['__%s_value' % field_name] = VDescriptor(
field_name, definition)
EDescriptor = self.eval_descriptors.get(
definition['type'], EvalDescriptor)
dict['__%s_eval' % field_name] = EDescriptor(
field_name, definition)
for method in self.config.get_proxy_methods(self.model_name):
setattr(mcs, method, getattr(proxy, method))
res = type.__new__(mcs, name, bases, dict)
getattr(_MODELS, models_key)[self.model_name] = res
return res
__new__.__doc__ = type.__new__.__doc__
return MetaModel
class ModelList(list):
'List for Model'
def __init__(self, definition, sequence=None, parent=None,
parent_field_name=''):
self.model_name = definition['relation']
if sequence is None:
sequence = []
self.parent = parent
if parent:
assert parent_field_name
self.parent_field_name = parent_field_name
self.parent_name = definition.get('relation_field', '')
self.domain = definition.get('domain', [])
self.context = definition.get('context')
self.add_remove = definition.get('add_remove')
self.record_removed = set()
self.record_deleted = set()
result = super(ModelList, self).__init__(sequence)
for record in self:
record._parent = parent
record._parent_field_name = parent_field_name
record._parent_name = self.parent_name
return result
__init__.__doc__ = list.__init__.__doc__
def _changed(self):
'Signal change to parent'
if self.parent:
self.parent._changed.add(self.parent_field_name)
self.parent._on_change([self.parent_field_name])
def _get_context(self):
from .pyson import PYSONDecoder
decoder = PYSONDecoder(_EvalEnvironment(self.parent))
ctx = self.parent._context.copy() if self.parent._context else {}
ctx.update(decoder.decode(self.context) if self.context else {})
return ctx
def __check(self, records):
config = None
for record in records:
assert isinstance(record, Model)
if self.parent:
assert record._config == self.parent._config
elif self:
assert record._config == self[0]._config
elif config:
assert record._config == config
else:
config = record._config
for record in records:
assert record._parent is None
assert not record._parent_field_name
assert not record._parent_name
record._parent = self.parent
record._parent_field_name = self.parent_field_name
record._parent_name = self.parent_name
# Set parent field to trigger on_change
if self.parent and self.parent_name in record._fields:
definition = record._fields[self.parent_name]
if definition['type'] in ('many2one', 'reference'):
setattr(record, self.parent_name, self.parent)
self.record_removed.difference_update(records)
self.record_deleted.difference_update(records)
def append(self, record):
self.__check([record])
res = super(ModelList, self).append(record)
self._changed()
return res
append.__doc__ = list.append.__doc__
def extend(self, iterable):
iterable = list(iterable)
self.__check(iterable)
res = super(ModelList, self).extend(iterable)
self._changed()
return res
extend.__doc__ = list.extend.__doc__
def insert(self, index, record):
raise NotImplementedError
insert.__doc__ = list.insert.__doc__
def pop(self, index=-1):
self.record_removed.add(self[index])
self[index]._parent = None
self[index]._parent_field_name = ''
self[index]._parent_name = ''
res = super(ModelList, self).pop(index)
self._changed()
return res
pop.__doc__ = list.pop.__doc__
def remove(self, record, _changed=True):
if record.id >= 0:
self.record_deleted.add(record)
record._parent = None
record._parent_field_name = ''
record._parent_name = ''
res = super(ModelList, self).remove(record)
if _changed:
self._changed()
return res
remove.__doc__ = list.remove.__doc__
def reverse(self):
raise NotImplementedError
reverse.__doc__ = list.reverse.__doc__
def sort(self):
raise NotImplementedError
sort.__doc__ = list.sort.__doc__
def new(self, **kwargs):
'Adds a new record to the ModelList and returns it'
Relation = Model.get(self.model_name, self.parent._config)
with Relation._config.set_context(self._get_context()):
new_record = Relation(**kwargs)
self.append(new_record)
return new_record
def find(self, condition=None, offset=0, limit=None, order=None):
'Returns records matching condition taking into account list domain'
from .pyson import PYSONDecoder
decoder = PYSONDecoder(_EvalEnvironment(self.parent))
Relation = Model.get(self.model_name, self.parent._config)
if condition is None:
condition = []
field_domain = decoder.decode(self.domain)
add_remove_domain = (decoder.decode(self.add_remove)
if self.add_remove else [])
new_domain = [field_domain, add_remove_domain, condition]
with Relation._config.set_context(self._get_context()):
return Relation.find(new_domain, offset, limit, order)
def set_sequence(self, field='sequence'):
changed = False
prev = None
for record in self:
if prev:
index = getattr(prev, field)
else:
index = None
update = False
value = getattr(record, field)
if value is None:
if index:
update = True
elif prev and record.id >= 0:
update = record.id < prev.id
if value == index:
if prev and record.id >= 0:
update = record.id < prev.id
elif value <= (index or 0):
update = True
if update:
if index is None:
index = 0
index += 1
setattr(record, field, index)
changed = record
prev = record
if changed:
self._changed()
class Model(object):
'Model class for Tryton records'
__counter = -1
_proxy = None
_config = None
_fields = None
def __init__(self, id=None, _default=True, **kwargs):
super(Model, self).__init__()
if id:
assert not kwargs
self.__id = id or Model.__counter
if self.__id < 0:
Model.__counter -= 1
self._values = {} # store the values of fields
self._changed = set() # store the changed fields
self._parent = None # store the parent record
self._parent_field_name = '' # store the field name in parent record
self._parent_name = '' # store the field name to parent record
self._context = self._config.context # store the context
if self.id < 0 and _default:
self._default_get()
for field_name, value in kwargs.iteritems():
definition = self._fields[field_name]
if definition['type'] in ('one2many', 'many2many'):
relation = Model.get(definition['relation'])
def instantiate(v):
if isinstance(v, (int, long)):
return relation(v)
elif isinstance(v, dict):
return relation(_default=_default, **v)
else:
return v
value = [instantiate(x) for x in value]
getattr(self, field_name).extend(value)
else:
if definition['type'] == 'many2one':
if isinstance(value, (int, long)):
relation = Model.get(definition['relation'])
value = relation(value)
setattr(self, field_name, value)
__init__.__doc__ = object.__init__.__doc__
@classmethod
def get(cls, name, config=None):
'Get a class for the named Model'
if (bytes == str) and isinstance(name, unicode):
name = name.encode('utf-8')
class Spam(Model):
__metaclass__ = MetaModelFactory(name, config=config)()
return Spam
@classmethod
def reset(cls, config=None, *names):
'Reset class definition for Models named'
config = config or proteus.config.get_config()
models_key = 'c%su%s' % (id(config), config.user)
if not names:
setattr(_MODELS, models_key, {})
else:
models = getattr(_MODELS, models_key, {})
for name in names:
del models[name]
def __str__(self):
return '<%s(%d)>' % (self.__class__.__name__, self.id)
__str__.__doc__ = object.__str__.__doc__
def __repr__(self):
if self._config == proteus.config.get_config():
return "proteus.Model.get('%s')(%d)" % (self.__class__.__name__,
self.id)
return "proteus.Model.get('%s', %s)(%d)" % (self.__class__.__name__,
repr(self._config), self.id)
__repr__.__doc__ = object.__repr__.__doc__
def __eq__(self, other):
if isinstance(other, Model):
return ((self.__class__.__name__, self.id) ==
(other.__class__.__name__, other.id))
return NotImplemented
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash(self.__class__.__name__) ^ hash(self.id)
def __int__(self):
return self.id
@property
def id(self):
'The unique ID'
return self.__id
@id.setter
def id(self, value):
assert self.__id < 0
self.__id = int(value)
@classmethod
def find(cls, condition=None, offset=0, limit=None, order=None):
'Return records matching condition'
if condition is None:
condition = []
ids = cls._proxy.search(condition, offset, limit, order,
cls._config.context)
return [cls(id) for id in ids]
@dualmethod
def reload(cls, records):
'Reload record'
for record in records:
record._values = {}
record._changed = set()
@dualmethod
def save(cls, records):
'Save records'
if not records:
return
proxy = records[0]._proxy
config = records[0]._config
context = config.context
create, write = [], []
for record in records:
assert proxy == record._proxy
assert config == record._config
if record.id < 0:
create.append(record)
elif record._changed:
write.append(record)
if create:
values = [r._get_values() for r in create]
ids = proxy.create(values, context)
for record, id_ in zip(create, ids):
record.id = id_
if write:
values = []
context['_timestamp'] = {}
for record in write:
values.append([record.id])
values.append(record._get_values(fields=record._changed))
context['_timestamp'].update(record._get_timestamp())
values.append(context)
proxy.write(*values)
for record in records:
record.reload()
@dualmethod
def delete(cls, records):
'Delete records'
if not records:
return
proxy = records[0]._proxy
config = records[0]._config
context = config.context
context['_timestamp'] = {}
delete = []
for record in records:
assert proxy == record._proxy
assert config == record._config
if record.id > 0:
context['_timestamp'].update(record._get_timestamp())
delete.append(record.id)
if delete:
proxy.delete(delete, context)
cls.reload(records)
@dualmethod
def duplicate(cls, records, default=None):
'Duplicate the record'
ids = cls._proxy.copy([r.id for r in records], default,
cls._config.context)
return [cls(id) for id in ids]
@dualmethod
def click(cls, records, button, change=None):
'Click on button'
if not records:
return
proxy = records[0]._proxy
context = records[0]._config.context
if change is None:
cls.save(records)
cls.reload(records) # Force reload because save doesn't always
return getattr(proxy, button)([r.id for r in records], context)
else:
record, = records
values = record._on_change_args(change)
changes = getattr(proxy, button)(values, context)
record._set_on_change(changes)
def _get_values(self, fields=None):
'Return dictionary values'
if fields is None:
fields = self._values.keys()
return dict((x, getattr(self, '__%s_value' % x)) for x in fields
if x not in ('id', '_timestamp'))
@property
def _timestamp(self):
'Get _timestamp'
return self._values.get('_timestamp')
def _get_timestamp(self):
'Return dictionary with timestamps'
result = {'%s,%s' % (self.__class__.__name__, self.id):
self._timestamp}
for field, definition in self._fields.iteritems():
if field not in self._values:
continue
if definition['type'] in ('one2many', 'many2many'):
for record in getattr(self, field):
result.update(record._get_timestamp())
return result
def _read(self, name):
'Read field'
fields = [name]
if name in self._values:
return
loading = self._fields[name]['loading']
if loading == 'eager':
fields = [x for x, y in self._fields.iteritems()
if y['loading'] == 'eager']
if not self._fields:
fields.append('_timestamp')
self._values.update(self._proxy.read([self.id], fields,
self._config.context)[0])
for field in fields:
if (field in self._fields
and self._fields[field]['type'] == 'float'
and isinstance(self._values[field], Decimal)):
# XML-RPC return Decimal for double
self._values[field] = float(self._values[field])
def _default_get(self):
'Set default values'
fields = self._fields.keys()
self._default_set(self._proxy.default_get(fields, False,
self._config.context))
def _default_set(self, values):
fieldnames = []
for field, value in values.iteritems():
if '.' in field:
continue
definition = self._fields[field]
if definition['type'] in ('one2many', 'many2many'):
if value and len(value) and isinstance(value[0], (int, long)):
self._values[field] = value
else:
relation = Model.get(definition['relation'], self._config)
records = []
for vals in (value or []):
record = relation()
record._default_set(vals)
records.append(record)
self._values[field] = ModelList(definition, records, self,
field)
else:
self._values[field] = value
fieldnames.append(field)
self._on_change(sorted(fieldnames))
def _get_eval(self):
values = dict((x, getattr(self, '__%s_eval' % x))
for x in self._fields if x != 'id')
values['id'] = self.id
return values
def _get_on_change_values(self, skip=None, fields=None):
values = {'id': self.id}
if fields:
definitions = ((f, self._fields[f]) for f in fields)
else:
definitions = self._fields.iteritems()
for field, definition in definitions:
if not fields:
if field == 'id' or (skip and field in skip):
continue
if (self.id >= 0
and (field not in self._values
or field not in self._changed)):
continue
if definition['type'] == 'one2many':
values[field] = [x._get_on_change_values(
skip={definition.get('relation_field', '')})
for x in getattr(self, field)]
elif (definition['type'] in ('many2one', 'reference')
and self._parent_name == definition['name']
and self._parent):
values[field] = self._parent._get_on_change_values(
skip={self._parent_field_name})
if definition['type'] == 'reference':
values[field] = (
self._parent.__class__.__name__, values[field])
else:
values[field] = getattr(self, '__%s_eval' % field)
return values
def _on_change_args(self, args):
res = {}
values = _EvalEnvironment(self, 'on_change')
for arg in args:
scope = values
for i in arg.split('.'):
if i not in scope:
break
scope = scope[i]
else:
res[arg] = scope
res['id'] = self.id
return res
def _on_change_set(self, field, value):
if (self._fields[field]['type'] in ('one2many', 'many2many')
and not isinstance(value, (list, tuple))):
to_remove = []
if value and value.get('remove'):
for record_id in value['remove']:
for record in getattr(self, field):
if record.id == record_id:
to_remove.append(record)
for record in to_remove:
# remove without signal
getattr(self, field).remove(record, _changed=False)
if value and (value.get('add') or value.get('update')):
for index, vals in value.get('add', []):
relation = Model.get(self._fields[field]['relation'],
self._config)
record = relation(_default=False)
record._set_on_change(vals)
# append without signal
if index == -1:
list.append(getattr(self, field), record)
else:
list.insert(getattr(self, field), index, record)
for vals in value.get('update', []):
if 'id' not in vals:
continue
for record in getattr(self, field):
if record.id == vals['id']:
record._set_on_change(vals)
elif (self._fields[field]['type'] in ('one2many', 'many2many')
and len(value) and not isinstance(value[0], (int, long))):
self._values[field] = []
for vals in value:
relation = Model.get(self._fields[field]['relation'],
self._config)
record = relation(_default=False, **vals)
getattr(self, field).append(record)
else:
self._values[field] = value
self._changed.add(field)
def _set_on_change(self, values):
later = {}
for field, value in values.iteritems():
if field not in self._fields:
continue
if self._fields[field]['type'] in ('one2many', 'many2many'):
later[field] = value
continue
self._on_change_set(field, value)
for field, value in later.iteritems():
self._on_change_set(field, value)
def _on_change(self, names):
'Call on_change for field'
# Import locally to not break installation
from proteus.pyson import PYSONDecoder
values = {}
for name in names:
definition = self._fields[name]
on_change = definition.get('on_change')
if not on_change:
continue
if isinstance(on_change, basestring):
definition['on_change'] = on_change = PYSONDecoder().decode(
on_change)
values.update(self._on_change_args(on_change))
if values:
context = self._config.context
changes = getattr(self._proxy, 'on_change')(values, names, context)
for change in changes:
self._set_on_change(change)
values = {}
fieldnames = set(names)
to_change = set()
later = set()
for field, definition in self._fields.iteritems():
on_change_with = definition.get('on_change_with')
if not on_change_with:
continue
if not fieldnames & set(on_change_with):
continue
if to_change & set(on_change_with):
later.add(field)
continue
to_change.add(field)
values.update(self._on_change_args(on_change_with))
if to_change:
context = self._config.context
changes = getattr(self._proxy, 'on_change_with')(values,
list(to_change), context)
self._set_on_change(changes)
for field in later:
on_change_with = self._fields[field]['on_change_with']
values = self._on_change_args(on_change_with)
context = self._config.context
result = getattr(self._proxy, 'on_change_with_%s' % field)(values,
context)
self._on_change_set(field, result)
if self._parent:
self._parent._changed.add(self._parent_field_name)
self._parent._on_change([self._parent_field_name])
class Wizard(object):
'Wizard class for Tryton wizards'
def __init__(self, name, models=None, action=None, config=None,
context=None):
if models:
assert len(set(type(x) for x in models)) == 1
super(Wizard, self).__init__()
self.name = name
self.form = None
self.form_state = None
self.actions = []
self._config = config or proteus.config.get_config()
self._context = context or {}
self._proxy = self._config.get_proxy(name, type='wizard')
result = self._proxy.create(self._config.context)
self.session_id, self.start_state, self.end_state = result
self.states = [self.start_state]
self.models = models
self.action = action
self.execute(self.start_state)
def execute(self, state):
assert state in self.states
self.state = state
while self.state != self.end_state:
ctx = self._context.copy()
ctx.update(self._config.context)
if self.models:
ctx['active_id'] = self.models[0].id
ctx['active_ids'] = [model.id for model in self.models]
ctx['active_model'] = self.models[0].__class__.__name__
else:
ctx['active_id'] = None
ctx['active_ids'] = None
ctx['active_model'] = None
if self.action:
ctx['action_id'] = self.action['id']
else:
ctx['action_id'] = None
if self.form:
# Filter only modified values
data = {self.form_state:
dict((k, v) for k, v in
self.form._get_on_change_values().iteritems()
if k in self.form._values)}
else:
data = {}
result = self._proxy.execute(self.session_id, data, self.state,
ctx)
if 'view' in result:
view = result['view']
self.form = Model.get(view['fields_view']['model'])()
self.form._default_set(view['defaults'])
self.states = [b['state'] for b in view['buttons']]
self.form_state = view['state']
else:
self.state = self.end_state
self.actions = []
for action in result.get('actions', []):
proteus_action = _convert_action(*action,
context=self._context)
if proteus_action:
self.actions.append(proteus_action)
if 'view' in result:
return
if self.state == self.end_state:
self._proxy.delete(self.session_id, self._config.context)
if self.models:
for record in self.models:
record.reload()
class Report(object):
'Report class for Tryton reports'
def __init__(self, name, config=None, context=None):
super(Report, self).__init__()
self.name = name
self._config = config or proteus.config.get_config()
self._context = context or {}
self._proxy = self._config.get_proxy(name, type='report')
def execute(self, models=None, data=None):
ids = [m.id for m in models] if models else data.get('ids', [])
if data is None:
data = {
'id': ids[0],
'ids': ids,
}
if models:
data['model'] = models[0].__class__.__name__
return self._proxy.execute(ids, data, self._context)
def _convert_action(action, data=None, context=None, config=None):
if config is None:
config = proteus.config.get_config()
if data is None:
data = {}
else:
data = data.copy()
if 'type' not in (action or {}):
return None
data['action_id'] = action['id']
if action['type'] == 'ir.action.act_window':
from .pyson import PYSONDecoder
action.setdefault('pyson_domain', '[]')
ctx = {
'active_model': data.get('model'),
'active_id': data.get('id'),
'active_ids': data.get('ids', []),
}
ctx.update(config.context)
ctx['_user'] = config.user
decoder = PYSONDecoder(ctx)
action_ctx = decoder.decode(action.get('pyson_context') or '{}')
ctx.update(action_ctx)
ctx.update(context)
action_ctx.update(context)
if 'date_format' not in action_ctx:
action_ctx['date_format'] = config.context.get(
'locale', {}).get('date', '%x')
ctx['context'] = ctx
decoder = PYSONDecoder(ctx)
domain = decoder.decode(action['pyson_domain'])
res_model = action.get('res_model', data.get('res_model'))
res_id = action.get('res_id', data.get('res_id'))
Model_ = Model.get(res_model)
with config.set_context(action_ctx):
if res_id is None:
return Model_.find(domain)
else:
return [Model_(id_) for id_ in res_id]
elif action['type'] == 'ir.action.wizard':
kwargs = {
'action': action,
'config': config,
'context': context,
}
if 'model' in data:
Model_ = Model.get(data['model'])
kwargs['models'] = [Model_(id_) for id_ in data.get('ids', [])]
return Wizard(action['wiz_name'], **kwargs)
elif action['type'] == 'ir.action.report':
ActionReport = Report(action['report_name'], context=context)
return ActionReport.execute(data=data)
elif action['type'] == 'ir.action.url':
return action.get('url')
proteus-4.6.1/proteus/tests/ 0000755 0001750 0001750 00000000000 13246073656 015412 5 ustar ced ced 0000000 0000000 proteus-4.6.1/proteus/tests/test_config.py 0000644 0001750 0001750 00000002702 13235121233 020250 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import proteus.config
from .common import ProteusTestCase
class TestConfig(ProteusTestCase):
def test_proxy(self):
config = proteus.config.get_config()
user_proxy = config.get_proxy('res.user')
user_id = user_proxy.search([('login', '=', 'admin')], 0, 1, None,
config.context)[0]
self.assert_(user_id == config.user)
def test_proxy_keyword(self):
config = proteus.config.get_config()
user_proxy = config.get_proxy('res.user')
user_id, = user_proxy.search(
[('login', '=', 'admin')], limit=1, context=config.context)
self.assert_(user_id == config.user)
def test_proxy_methods(self):
config = proteus.config.get_config()
self.assert_('search' in config.get_proxy_methods('res.user'))
def test_trytond_config_eq(self):
config1 = proteus.config.get_config()
proteus.config.set_trytond()
config2 = proteus.config.get_config()
self.assertEqual(config1, config2)
self.assertRaises(NotImplementedError, config1.__eq__, None)
def test_repr(self):
config = proteus.config.TrytondConfig('sqlite:///:memory:')
self.assertEqual(repr(config),
"proteus.config.TrytondConfig("
"'sqlite:///:memory:', 'admin', config_file=None)")
proteus-4.6.1/proteus/tests/test_wizard.py 0000644 0001750 0001750 00000004137 13235121233 020307 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from proteus import Wizard, Model
from .common import ProteusTestCase
class TestWizard(ProteusTestCase):
def test_translation_clean(self):
translation_clean = Wizard('ir.translation.clean')
self.assertEqual(translation_clean.form.__class__.__name__,
'ir.translation.clean.start')
translation_clean.execute('clean')
self.assertEqual(translation_clean.form.__class__.__name__,
'ir.translation.clean.succeed')
def test_translation_export(self):
Lang = Model.get('ir.lang')
Module = Model.get('ir.module')
translation_export = Wizard('ir.translation.export')
translation_export.form.language, = Lang.find([('code', '=', 'en')])
translation_export.form.module, = Module.find([('name', '=', 'ir')])
translation_export.execute('export')
self.assert_(translation_export.form.file)
translation_export.execute('end')
def test_user_config(self):
User = Model.get('res.user')
user_config = Wizard('res.user.config')
user_config.execute('user')
user_config.form.name = 'Foo'
user_config.form.login = 'foo'
user_config.execute('add')
self.assertEqual(user_config.form.name, None)
self.assertEqual(user_config.form.login, None)
user_config.form.name = 'Bar'
user_config.form.login = 'bar'
user_config.execute('end')
self.assert_(User.find([('name', '=', 'Foo')]))
self.assertFalse(User.find([('name', '=', 'Bar')]))
def test_translation_update(self):
print_model_graph = Wizard('ir.translation.update')
self.assertEqual(len(print_model_graph.actions), 0)
print_model_graph.execute('update')
self.assertEqual(len(print_model_graph.actions), 1)
def test_configuration_wizard(self):
config_wizard = Wizard('ir.module.config_wizard')
config_wizard.execute('action')
self.assertTrue(config_wizard.actions)
proteus-4.6.1/proteus/tests/test_report.py 0000644 0001750 0001750 00000001427 13175640537 020341 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import unittest
try:
import pydot
except ImportError:
pydot = None
from proteus import Report, Model
from .common import ProteusTestCase
class TestReport(ProteusTestCase):
@unittest.skipIf(not pydot, 'requires pydot')
def test_model_graph(self):
IrModel = Model.get('ir.model')
models = IrModel.find([])
data = {
'level': 1,
'filter': '',
}
report = Report('ir.model.graph')
type_, data, print_, name = report.execute(models, data)
self.assertEqual(type_, 'png')
self.assertEqual(print_, False)
self.assertEqual(name, 'Graph')
proteus-4.6.1/proteus/tests/test_model.py 0000644 0001750 0001750 00000025734 13235121233 020115 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from proteus import Model
from .common import ProteusTestCase
class TestModel(ProteusTestCase):
def test_class_cache(self):
User1 = Model.get('res.user')
User2 = Model.get('res.user')
self.assertEqual(id(User1), id(User2))
Model.reset()
User3 = Model.get('res.user')
self.assertNotEqual(id(User1), id(User3))
def test_class_method(self):
User = Model.get('res.user')
self.assert_(len(User.search([('login', '=', 'admin')], {})))
def test_int(self):
User = Model.get('res.user')
admin = User.find([('login', '=', 'admin')])[0]
self.assertEqual(int(admin), admin.id)
def test_find(self):
User = Model.get('res.user')
admin = User.find([('login', '=', 'admin')])[0]
self.assertEqual(admin.login, 'admin')
def test_many2one(self):
User = Model.get('res.user')
admin = User.find([('login', '=', 'admin')])[0]
self.assert_(isinstance(admin.create_uid, User))
try:
admin.create_uid = 'test'
self.fail()
except AssertionError:
pass
admin.create_uid = admin
admin.create_uid = None
User(write_uid=None)
def test_one2many(self):
Group = Model.get('res.group')
administration = Group.find([('name', '=', 'Administration')])[0]
self.assert_(isinstance(administration.model_access, list))
self.assert_(isinstance(administration.model_access[0],
Model.get('ir.model.access')))
try:
administration.model_access = []
self.fail()
except AttributeError:
pass
def test_many2many(self):
User = Model.get('res.user')
admin = User.find([('login', '=', 'admin')])[0]
self.assert_(isinstance(admin.groups, list))
self.assert_(isinstance(admin.groups[0],
Model.get('res.group')))
try:
admin.groups = []
self.fail()
except AttributeError:
pass
# TODO test date
def test_reference(self):
Attachment = Model.get('ir.attachment')
User = Model.get('res.user')
admin = User.find([('login', '=', 'admin')])[0]
attachment = Attachment()
attachment.name = 'Test'
attachment.resource = admin
attachment.save()
self.assertEqual(attachment.resource, admin)
def test_id_counter(self):
User = Model.get('res.user')
test1 = User()
self.assert_(test1.id < 0)
test2 = User()
self.assert_(test2.id < 0)
self.assertNotEqual(test1.id, test2.id)
def test_init(self):
User = Model.get('res.user')
self.assertEqual(User(1).id, 1)
self.assertEqual(User(name='Foo').name, 'Foo')
Lang = Model.get('ir.lang')
en, = Lang.find([('code', '=', 'en')])
self.assertEqual(User(language=en).language, en)
self.assertEqual(User(language=en.id).language, en)
Group = Model.get('res.group')
groups = Group.find()
self.assertEqual(len(User(groups=groups).groups), len(groups))
self.assertEqual(len(User(groups=[x.id for x in groups]).groups),
len(groups))
def test_save(self):
User = Model.get('res.user')
test = User()
test.name = 'Test'
test.login = 'test'
test.save()
self.assert_(test.id > 0)
test = User(test.id)
self.assertEqual(test.name, 'Test')
self.assertEqual(test.login, 'test')
self.assert_(test.active)
test.signature = 'Test signature'
self.assertEqual(test.signature, 'Test signature')
test.save()
self.assertEqual(test.signature, 'Test signature')
test = User(test.id)
self.assertEqual(test.signature, 'Test signature')
Group = Model.get('res.group')
test2 = User(name='Test 2', login='test2',
groups=[Group(name='Test 2')])
test2.save()
self.assert_(test2.id > 0)
self.assertEqual(test2.name, 'Test 2')
self.assertEqual(test2.login, 'test2')
test.signature = 'classmethod save'
test2.name = 'Test 2 classmethod'
test3 = User(name='Test 3', login='test3')
User.save([test, test2, test3])
self.assertEqual(test.signature, 'classmethod save')
self.assertEqual(test2.name, 'Test 2 classmethod')
self.assert_(test3.id > 0)
self.assertEqual(test3.name, 'Test 3')
def test_save_many2one(self):
User = Model.get('res.user')
test = User()
test.name = 'Test save many2one'
test.login = 'test_save_many2one'
test.save()
Lang = Model.get('ir.lang')
en, = Lang.find([('code', '=', 'en')])
test.language = en
test.save()
self.assertEqual(test.language, en)
test.language = None
test.save()
self.assertFalse(test.language)
def test_save_one2many(self):
Group = Model.get('res.group')
group = Group()
group.name = 'Test save one2many'
group.save()
ModelAccess = Model.get('ir.model.access')
Model_ = Model.get('ir.model')
model_access = ModelAccess()
model_access.model = Model_.find([('model', '=', 'res.group')])[0]
model_access.perm_read = True
model_access.perm_write = True
model_access.perm_create = True
model_access.perm_delete = True
group.model_access.append(model_access)
group.save()
self.assertEqual(len(group.model_access), 1)
model_access_id = group.model_access[0].id
group.name = 'Test save one2many bis'
group.model_access[0].description = 'Test save one2many'
group.save()
self.assertEqual(group.model_access[0].description,
'Test save one2many')
group.model_access.pop()
group.save()
self.assertEqual(group.model_access, [])
self.assertEqual(len(ModelAccess.find([('id', '=', model_access_id)])),
1)
group.model_access.append(ModelAccess(model_access_id))
group.save()
self.assertEqual(len(group.model_access), 1)
group.model_access.remove(group.model_access[0])
group.save()
self.assertEqual(group.model_access, [])
self.assertEqual(len(ModelAccess.find([('id', '=', model_access_id)])),
0)
def test_save_many2many(self):
User = Model.get('res.user')
test = User()
test.name = 'Test save many2many'
test.login = 'test_save_many2many'
test.save()
Group = Model.get('res.group')
group = Group()
group.name = 'Test save many2many'
group.save()
test.groups.append(group)
test.save()
self.assertEqual(len(test.groups), 1)
group_id = test.groups[0].id
test.name = 'Test save many2many bis'
test.groups[0].name = 'Test save many2many bis'
test.save()
self.assertEqual(test.groups[0].name,
'Test save many2many bis')
test.groups.pop()
test.save()
self.assertEqual(test.groups, [])
self.assertEqual(len(Group.find([('id', '=', group_id)])), 1)
test.groups.append(Group(group_id))
test.save()
self.assertEqual(len(test.groups), 1)
test.groups.remove(test.groups[0])
test.save()
self.assertEqual(test.groups, [])
self.assertEqual(len(Group.find([('id', '=', group_id)])), 0)
def test_eq(self):
User = Model.get('res.user')
test = User()
test.name = 'Test eq'
test.login = 'test_eq'
test.save()
admin1 = User.find([('login', '=', 'admin')])[0]
admin2 = User.find([('login', '=', 'admin')])[0]
self.assertEqual(admin1, admin2)
self.assertFalse(admin1 != admin2)
self.assertNotEqual(admin1, test)
self.assertFalse(admin1 == test)
self.assertNotEqual(admin1, None)
self.assertNotEqual(admin1, False)
self.assertNotEqual(admin1, 1)
def test_default_set(self):
User = Model.get('res.user')
Group = Model.get('res.group')
group_ids = [x.id for x in Group.find()]
test = User()
test._default_set({
'name': 'Test',
'groups': group_ids,
})
self.assertEqual(test.name, 'Test')
self.assertEqual([x.id for x in test.groups], group_ids)
test = User()
test._default_set({
'name': 'Test',
'groups': [
{
'name': 'Group 1',
},
{
'name': 'Group 2',
},
],
})
self.assertEqual(test.name, 'Test')
self.assertEqual([x.name for x in test.groups], ['Group 1', 'Group 2'])
def test_delete(self):
Group = Model.get('res.group')
test = Group()
test.name = 'Test delete'
test.login = 'test delete'
test.save()
test.delete()
def test_duplicate(self):
User = Model.get('res.user')
test = User()
test.name = 'Test duplicate'
test.login = 'test duplicate'
test.save()
copy, = User.duplicate([test], {'name': 'Test copy'})
self.assertEqual(copy.name, 'Test copy')
self.assertEqual(copy.login, 'test duplicate (copy)')
self.assertNotEqual(copy.id, test.id)
def test_on_change(self):
Trigger = Model.get('ir.trigger')
trigger = Trigger()
trigger.on_time = True
self.assertEqual(trigger.on_create, False)
trigger.on_create = True
self.assertEqual(trigger.on_time, False)
def test_on_change_with(self):
Attachment = Model.get('ir.attachment')
attachment = Attachment()
attachment.description = 'Test'
self.assertEqual(attachment.summary, 'Test')
def test_on_change_set(self):
User = Model.get('res.user')
Group = Model.get('res.group')
test = User()
test._on_change_set('name', 'Test')
self.assertEqual(test.name, 'Test')
group_ids = [x.id for x in Group.find()]
test._on_change_set('groups', group_ids)
self.assertEqual([x.id for x in test.groups], group_ids)
test._on_change_set('groups', {'remove': [group_ids[0]]})
self.assertEqual([x.id for x in test.groups], group_ids[1:])
test._on_change_set('groups', {'add': [(-1, {
'name': 'Bar',
})]})
self.assert_([x for x in test.groups if x.name == 'Bar'])
test.groups.extend(Group.find())
group = test.groups[0]
test._on_change_set('groups', {'update': [{
'id': group.id,
'name': 'Foo',
}]})
self.assert_([x for x in test.groups if x.name == 'Foo'])
proteus-4.6.1/proteus/tests/test_context.py 0000644 0001750 0001750 00000001064 13175640537 020507 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of this
# repository contains the full copyright notices and license terms.
from .common import ProteusTestCase
class TestContext(ProteusTestCase):
def test_config(self):
prev_ctx = self.config._context
with self.config.set_context({'a': 1}):
self.assertEqual(self.config.context['a'], 1)
for key, value in prev_ctx.items():
self.assertEqual(self.config.context[key], value)
self.assertEqual(self.config.context, prev_ctx)
proteus-4.6.1/proteus/tests/common.py 0000644 0001750 0001750 00000000707 13175640537 017257 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from unittest import TestCase
from trytond.tests.test_tryton import db_exist, create_db
from proteus import config
class ProteusTestCase(TestCase):
@classmethod
def setUpClass(cls):
if not db_exist():
create_db()
def setUp(self):
self.config = config.set_trytond()
proteus-4.6.1/proteus/tests/__init__.py 0000644 0001750 0001750 00000003250 13175640537 017522 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import os
import sys
import unittest
import doctest
import proteus
import proteus.config
os.environ.setdefault('TRYTOND_DATABASE_URI', 'sqlite:///:memory:')
os.environ.setdefault('DB_NAME', ':memory:')
from trytond.tests.test_tryton import doctest_setup, doctest_teardown
here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))
def test_suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for filename in os.listdir(os.path.dirname(__file__)):
if filename.startswith("test") and filename.endswith(".py"):
modname = "proteus.tests." + filename[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
suite.addTests(additional_tests())
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (proteus, proteus.config):
suite.addTest(doctest.DocTestSuite(mod))
if os.path.isfile(readme):
suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
setUp=doctest_setup, tearDown=doctest_teardown,
encoding='utf-8',
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
return runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))))
sys.exit(not main().wasSuccessful())
proteus-4.6.1/proteus/config.py 0000644 0001750 0001750 00000024555 13235121233 016061 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
"""
Configuration functions for the proteus package for Tryton.
"""
from __future__ import with_statement
__all__ = ['set_trytond', 'set_xmlrpc', 'get_config']
import xmlrpclib
import threading
from decimal import Decimal
import datetime
import os
import urlparse
def dump_decimal(self, value, write):
value = {'__class__': 'Decimal',
'decimal': str(value),
}
self.dump_struct(value, write)
def dump_bytes(self, value, write):
self.write = write
value = xmlrpclib.Binary(value)
value.encode(self)
del self.write
def dump_date(self, value, write):
value = {'__class__': 'date',
'year': value.year,
'month': value.month,
'day': value.day,
}
self.dump_struct(value, write)
def dump_time(self, value, write):
value = {'__class__': 'time',
'hour': value.hour,
'minute': value.minute,
'second': value.second,
'microsecond': value.microsecond,
}
self.dump_struct(value, write)
def dump_timedelta(self, value, write):
value = {'__class__': 'timedelta',
'seconds': value.total_seconds(),
}
self.dump_struct(value, write)
xmlrpclib.Marshaller.dispatch[Decimal] = dump_decimal
xmlrpclib.Marshaller.dispatch[datetime.date] = dump_date
xmlrpclib.Marshaller.dispatch[datetime.time] = dump_time
xmlrpclib.Marshaller.dispatch[datetime.timedelta] = dump_timedelta
if bytes != str:
xmlrpclib.Marshaller.dispatch[bytes] = dump_bytes
xmlrpclib.Marshaller.dispatch[bytearray] = dump_bytes
class XMLRPCDecoder(object):
decoders = {}
@classmethod
def register(cls, klass, decoder):
assert klass not in cls.decoders
cls.decoders[klass] = decoder
def __call__(self, dct):
if dct.get('__class__') in self.decoders:
return self.decoders[dct['__class__']](dct)
return dct
XMLRPCDecoder.register('date',
lambda dct: datetime.date(dct['year'], dct['month'], dct['day']))
XMLRPCDecoder.register('time',
lambda dct: datetime.time(dct['hour'], dct['minute'], dct['second'],
dct['microsecond']))
XMLRPCDecoder.register('timedelta',
lambda dct: datetime.timedelta(seconds=dct['seconds']))
XMLRPCDecoder.register('Decimal', lambda dct: Decimal(dct['decimal']))
def end_struct(self, data):
mark = self._marks.pop()
# map structs to Python dictionaries
dct = {}
items = self._stack[mark:]
for i in range(0, len(items), 2):
dct[items[i]] = items[i + 1]
dct = XMLRPCDecoder()(dct)
self._stack[mark:] = [dct]
self._value = 0
xmlrpclib.Unmarshaller.dispatch['struct'] = end_struct
_CONFIG = threading.local()
_CONFIG.current = None
class ContextManager(object):
'Context Manager for the tryton context'
def __init__(self, config):
self.config = config
self.context = config.context
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.config._context = self.context
class Config(object):
'Config interface'
def __init__(self):
super(Config, self).__init__()
self._context = {}
@property
def context(self):
return self._context.copy()
def set_context(self, context=None, **kwargs):
ctx_manager = ContextManager(self)
if context is None:
context = {}
self._context = self.context
self._context.update(context)
self._context.update(kwargs)
return ctx_manager
def get_proxy(self, name):
raise NotImplementedError
def get_proxy_methods(self, name):
raise NotImplementedError
class _TrytondMethod(object):
def __init__(self, name, model, config):
super(_TrytondMethod, self).__init__()
self._name = name
self._object = model
self._config = config
def __call__(self, *args, **kwargs):
from trytond.rpc import RPC
from trytond.tools import is_instance_method
from trytond.transaction import Transaction
if self._name in self._object.__rpc__:
rpc = self._object.__rpc__[self._name]
elif self._name in getattr(self._object, '_buttons', {}):
rpc = RPC(readonly=False, instantiate=0)
else:
raise TypeError('%s is not callable' % self._name)
with Transaction().start(self._config.database_name,
self._config.user, readonly=rpc.readonly) as transaction:
args, kwargs, transaction.context, transaction.timestamp = \
rpc.convert(self._object, *args, **kwargs)
meth = getattr(self._object, self._name)
if (rpc.instantiate is None
or not is_instance_method(self._object, self._name)):
result = rpc.result(meth(*args, **kwargs))
else:
assert rpc.instantiate == 0
inst = args.pop(0)
if hasattr(inst, self._name):
result = rpc.result(meth(inst, *args, **kwargs))
else:
result = [rpc.result(meth(i, *args, **kwargs))
for i in inst]
if not rpc.readonly:
transaction.commit()
return result
class TrytondProxy(object):
'Proxy for function call for trytond'
def __init__(self, name, config, type='model'):
super(TrytondProxy, self).__init__()
self._config = config
self._object = config.pool.get(name, type=type)
__init__.__doc__ = object.__init__.__doc__
def __getattr__(self, name):
'Return attribute value'
return _TrytondMethod(name, self._object, self._config)
class TrytondConfig(Config):
'Configuration for trytond'
def __init__(self, database=None, user='admin', config_file=None):
super(TrytondConfig, self).__init__()
if not database:
database = os.environ.get('TRYTOND_DATABASE_URI')
else:
os.environ['TRYTOND_DATABASE_URI'] = database
if not config_file:
config_file = os.environ.get('TRYTOND_CONFIG')
from trytond.config import config
config.update_etc(config_file)
from trytond.pool import Pool
from trytond.transaction import Transaction
self.database = database
database_name = None
if database:
uri = urlparse.urlparse(database)
database_name = uri.path.strip('/')
if not database_name:
database_name = os.environ['DB_NAME']
self.database_name = database_name
self._user = user
self.config_file = config_file
Pool.start()
self.pool = Pool(database_name)
self.pool.init()
with Transaction().start(self.database_name, 0) as transaction:
User = self.pool.get('res.user')
transaction.context = self.context
self.user = User.search([
('login', '=', user),
], limit=1)[0].id
with transaction.set_user(self.user):
self._context = User.get_preferences(context_only=True)
__init__.__doc__ = object.__init__.__doc__
def __repr__(self):
return ("proteus.config.TrytondConfig"
"(%s, %s, config_file=%s)"
% (repr(self.database), repr(self._user), repr(self.config_file)))
__repr__.__doc__ = object.__repr__.__doc__
def __eq__(self, other):
if not isinstance(other, TrytondConfig):
raise NotImplementedError
return (self.database_name == other.database_name
and self._user == other._user
and self.database == other.database
and self.config_file == other.config_file)
def __hash__(self):
return hash((self.database_name, self._user,
self.database, self.config_file))
def get_proxy(self, name, type='model'):
'Return Proxy class'
return TrytondProxy(name, self, type=type)
def get_proxy_methods(self, name, type='model'):
'Return list of methods'
proxy = self.get_proxy(name, type=type)
methods = [x for x in proxy._object.__rpc__]
if hasattr(proxy._object, '_buttons'):
methods += [x for x in proxy._object._buttons]
return methods
def set_trytond(database=None, user='admin',
config_file=None):
'Set trytond package as backend'
_CONFIG.current = TrytondConfig(database, user, config_file=config_file)
return _CONFIG.current
class XmlrpcProxy(object):
'Proxy for function call for XML-RPC'
def __init__(self, name, config, type='model'):
super(XmlrpcProxy, self).__init__()
self._config = config
self._object = getattr(config.server, '%s.%s' % (type, name))
__init__.__doc__ = object.__init__.__doc__
def __getattr__(self, name):
'Return attribute value'
return getattr(self._object, name)
class XmlrpcConfig(Config):
'Configuration for XML-RPC'
def __init__(self, url, **kwargs):
super(XmlrpcConfig, self).__init__()
self.url = url
self.server = xmlrpclib.ServerProxy(
url, allow_none=1, use_datetime=1, **kwargs)
# TODO add user
self.user = None
self._context = self.server.model.res.user.get_preferences(True, {})
__init__.__doc__ = object.__init__.__doc__
def __repr__(self):
return "proteus.config.XmlrpcConfig(%s)" % repr(self.url)
__repr__.__doc__ = object.__repr__.__doc__
def __eq__(self, other):
if not isinstance(other, XmlrpcConfig):
raise NotImplementedError
return self.url == other.url
def __hash__(self):
return hash(self.url)
def get_proxy(self, name, type='model'):
'Return Proxy class'
return XmlrpcProxy(name, self, type=type)
def get_proxy_methods(self, name, type='model'):
'Return list of methods'
object_ = '%s.%s' % (type, name)
return [x[len(object_) + 1:]
for x in self.server.system.listMethods()
if x.startswith(object_)
and '.' not in x[len(object_) + 1:]]
def set_xmlrpc(url, **kwargs):
'''
Set XML-RPC as backend.
It pass the keyword arguments received to xmlrpclib.ServerProxy()
'''
_CONFIG.current = XmlrpcConfig(url, **kwargs)
return _CONFIG.current
def get_config():
return _CONFIG.current
proteus-4.6.1/proteus/pyson.py 0000644 0001750 0001750 00000046205 13235121233 015760 0 ustar ced ced 0000000 0000000 # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
__all__ = ['PYSONEncoder', 'PYSONDecoder', 'Eval', 'Not', 'Bool', 'And', 'Or',
'Equal', 'Greater', 'Less', 'If', 'Get', 'In', 'Date', 'DateTime', 'Len']
import json
import datetime
from dateutil.relativedelta import relativedelta
from functools import reduce, wraps
def reduced_type(types):
types = types.copy()
for k, r in [(long, int), (str, basestring), (unicode, basestring)]:
if k in types:
types.remove(k)
types.add(r)
return types
def reduce_type(func):
@wraps(func)
def wrapper(*args, **kwargs):
return reduced_type(func(*args, **kwargs))
return wrapper
class PYSON(object):
def pyson(self):
raise NotImplementedError
def types(self):
raise NotImplementedError
@staticmethod
def eval(dct, context):
raise NotImplementedError
def __invert__(self):
if self.types() != set([bool]):
return Not(Bool(self))
else:
return Not(self)
def __and__(self, other):
if (isinstance(other, PYSON)
and other.types() != set([bool])):
other = Bool(other)
if (isinstance(self, And)
and not isinstance(self, Or)):
self._statements.append(other)
return self
if self.types() != set([bool]):
return And(Bool(self), other)
else:
return And(self, other)
__rand__ = __and__
def __or__(self, other):
if (isinstance(other, PYSON)
and other.types() != set([bool])):
other = Bool(other)
if isinstance(self, Or):
self._statements.append(other)
return self
if self.types() != set([bool]):
return Or(Bool(self), other)
else:
return Or(self, other)
__ror__ = __or__
def __eq__(self, other):
return Equal(self, other)
def __ne__(self, other):
return Not(Equal(self, other))
def __gt__(self, other):
return Greater(self, other)
def __ge__(self, other):
return Greater(self, other, True)
def __lt__(self, other):
return Less(self, other)
def __le__(self, other):
return Less(self, other, True)
def get(self, k, d=''):
return Get(self, k, d)
def in_(self, obj):
return In(self, obj)
def contains(self, k):
return In(k, self)
def __repr__(self):
klass = self.__class__.__name__
return '%s(%s)' % (klass, ', '.join(map(repr, self.__repr_params__)))
@property
def __repr_params__(self):
return NotImplementedError
class PYSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, PYSON):
return obj.pyson()
elif isinstance(obj, datetime.date):
if isinstance(obj, datetime.datetime):
return DateTime(obj.year, obj.month, obj.day,
obj.hour, obj.minute, obj.second, obj.microsecond
).pyson()
else:
return Date(obj.year, obj.month, obj.day).pyson()
return super(PYSONEncoder, self).default(obj)
class PYSONDecoder(json.JSONDecoder):
def __init__(self, context=None, noeval=False):
self.__context = context or {}
self.noeval = noeval
super(PYSONDecoder, self).__init__(object_hook=self._object_hook)
def _object_hook(self, dct):
if '__class__' in dct:
klass = CONTEXT.get(dct['__class__'])
if klass:
if not self.noeval:
return klass.eval(dct, self.__context)
else:
dct = dct.copy()
del dct['__class__']
return klass(**dct)
return dct
class Eval(PYSON):
def __init__(self, v, d=''):
super(Eval, self).__init__()
self._value = v
self._default = d
@property
def __repr_params__(self):
return self._value, self._default
def pyson(self):
return {
'__class__': 'Eval',
'v': self._value,
'd': self._default,
}
@reduce_type
def types(self):
if isinstance(self._default, PYSON):
return self._default.types()
else:
return set([type(self._default)])
@staticmethod
def eval(dct, context):
return context.get(dct['v'], dct['d'])
class Not(PYSON):
def __init__(self, v):
super(Not, self).__init__()
if isinstance(v, PYSON):
assert v.types() == set([bool]), 'value must be boolean'
else:
assert isinstance(v, bool), 'value must be boolean'
self._value = v
@property
def __repr_params__(self):
return (self._value,)
def pyson(self):
return {
'__class__': 'Not',
'v': self._value,
}
def types(self):
return set([bool])
@staticmethod
def eval(dct, context):
return not dct['v']
class Bool(PYSON):
def __init__(self, v):
super(Bool, self).__init__()
self._value = v
@property
def __repr_params__(self):
return (self._value,)
def pyson(self):
return {
'__class__': 'Bool',
'v': self._value,
}
def types(self):
return set([bool])
@staticmethod
def eval(dct, context):
return bool(dct['v'])
class And(PYSON):
def __init__(self, *statements, **kwargs):
super(And, self).__init__()
statements = list(statements) + kwargs.get('s', [])
for statement in statements:
if isinstance(statement, PYSON):
assert statement.types() == set([bool]), \
'statement must be boolean'
else:
assert isinstance(statement, bool), \
'statement must be boolean'
assert len(statements) >= 2, 'must have at least 2 statements'
self._statements = statements
@property
def __repr_params__(self):
return tuple(self._statements)
def pyson(self):
return {
'__class__': 'And',
's': self._statements,
}
def types(self):
return set([bool])
@staticmethod
def eval(dct, context):
return bool(reduce(lambda x, y: x and y, dct['s']))
class Or(And):
def pyson(self):
res = super(Or, self).pyson()
res['__class__'] = 'Or'
return res
@staticmethod
def eval(dct, context):
return bool(reduce(lambda x, y: x or y, dct['s']))
class Equal(PYSON):
def __init__(self, s1, s2):
statement1, statement2 = s1, s2
super(Equal, self).__init__()
if isinstance(statement1, PYSON):
types1 = statement1.types()
else:
types1 = reduced_type(set([type(s1)]))
if isinstance(statement2, PYSON):
types2 = statement2.types()
else:
types2 = reduced_type(set([type(s2)]))
assert types1 == types2, 'statements must have the same type'
self._statement1 = statement1
self._statement2 = statement2
@property
def __repr_params__(self):
return (self._statement1, self._statement2)
def pyson(self):
return {
'__class__': 'Equal',
's1': self._statement1,
's2': self._statement2,
}
def types(self):
return set([bool])
@staticmethod
def eval(dct, context):
return dct['s1'] == dct['s2']
class Greater(PYSON):
def __init__(self, s1, s2, e=False):
statement1, statement2, equal = s1, s2, e
super(Greater, self).__init__()
for i in (statement1, statement2):
if isinstance(i, PYSON):
assert i.types().issubset({int, long, float, type(None)}), \
'statement must be an integer or a float'
else:
assert isinstance(i, (int, long, float, type(None))), \
'statement must be an integer or a float'
if isinstance(equal, PYSON):
assert equal.types() == set([bool])
else:
assert isinstance(equal, bool)
self._statement1 = statement1
self._statement2 = statement2
self._equal = equal
@property
def __repr_params__(self):
return (self._statement1, self._statement2, self._equal)
def pyson(self):
return {
'__class__': 'Greater',
's1': self._statement1,
's2': self._statement2,
'e': self._equal,
}
def types(self):
return set([bool])
@staticmethod
def _convert(dct):
for i in ('s1', 's2'):
if dct[i] is None:
dct[i] = 0.0
if not isinstance(dct[i], (int, long, float)):
dct = dct.copy()
dct[i] = float(dct[i])
return dct
@staticmethod
def eval(dct, context):
dct = Greater._convert(dct)
if dct['e']:
return dct['s1'] >= dct['s2']
else:
return dct['s1'] > dct['s2']
class Less(Greater):
def pyson(self):
res = super(Less, self).pyson()
res['__class__'] = 'Less'
return res
@staticmethod
def eval(dct, context):
dct = Less._convert(dct)
if dct['e']:
return dct['s1'] <= dct['s2']
else:
return dct['s1'] < dct['s2']
class If(PYSON):
def __init__(self, c, t, e=None):
condition, then_statement, else_statement = c, t, e
super(If, self).__init__()
if isinstance(condition, PYSON):
assert condition.types() == set([bool]), \
'condition must be boolean'
else:
assert isinstance(condition, bool), 'condition must be boolean'
if isinstance(then_statement, PYSON):
then_types = then_statement.types()
else:
then_types = reduced_type(set([type(then_statement)]))
if isinstance(else_statement, PYSON):
else_types = else_statement.types()
else:
else_types = reduced_type(set([type(else_statement)]))
assert then_types == else_types, \
'then and else statements must be the same type'
self._condition = condition
self._then_statement = then_statement
self._else_statement = else_statement
@property
def __repr_params__(self):
return (self._condition, self._then_statement, self._else_statement)
def pyson(self):
return {
'__class__': 'If',
'c': self._condition,
't': self._then_statement,
'e': self._else_statement,
}
@reduce_type
def types(self):
if isinstance(self._then_statement, PYSON):
return self._then_statement.types()
else:
return set([type(self._then_statement)])
@staticmethod
def eval(dct, context):
if dct['c']:
return dct['t']
else:
return dct['e']
class Get(PYSON):
def __init__(self, v, k, d=''):
obj, key, default = v, k, d
super(Get, self).__init__()
if isinstance(obj, PYSON):
assert obj.types() == set([dict]), 'obj must be a dict'
else:
assert isinstance(obj, dict), 'obj must be a dict'
self._obj = obj
if isinstance(key, PYSON):
assert key.types() == set([basestring]), 'key must be a string'
else:
assert isinstance(key, basestring), 'key must be a string'
self._key = key
self._default = default
@property
def __repr_params__(self):
return (self._obj, self._key, self._default)
def pyson(self):
return {
'__class__': 'Get',
'v': self._obj,
'k': self._key,
'd': self._default,
}
@reduce_type
def types(self):
if isinstance(self._default, PYSON):
return self._default.types()
else:
return set([type(self._default)])
@staticmethod
def eval(dct, context):
return dct['v'].get(dct['k'], dct['d'])
class In(PYSON):
def __init__(self, k, v):
key, obj = k, v
super(In, self).__init__()
if isinstance(key, PYSON):
assert key.types().issubset(set([basestring, int])), \
'key must be a string or an integer or a long'
else:
assert isinstance(key, (basestring, int, long)), \
'key must be a string or an integer or a long'
if isinstance(obj, PYSON):
assert obj.types().issubset(set([dict, list])), \
'obj must be a dict or a list'
if obj.types() == set([dict]):
assert isinstance(key, basestring), 'key must be a string'
else:
assert isinstance(obj, (dict, list))
if isinstance(obj, dict):
assert isinstance(key, basestring), 'key must be a string'
self._key = key
self._obj = obj
@property
def __repr_params__(self):
return (self._key, self._obj)
def pyson(self):
return {
'__class__': 'In',
'k': self._key,
'v': self._obj,
}
def types(self):
return set([bool])
@staticmethod
def eval(dct, context):
return dct['k'] in dct['v']
class Date(PYSON):
def __init__(self, year=None, month=None, day=None,
delta_years=0, delta_months=0, delta_days=0, **kwargs):
year = kwargs.get('y', year)
month = kwargs.get('M', month)
day = kwargs.get('d', day)
delta_years = kwargs.get('dy', delta_years)
delta_months = kwargs.get('dM', delta_months)
delta_days = kwargs.get('dd', delta_days)
super(Date, self).__init__()
for i in (year, month, day, delta_years, delta_months, delta_days):
if isinstance(i, PYSON):
assert i.types().issubset(set([int, long, type(None)])), \
'%s must be an integer or None' % (i,)
else:
assert isinstance(i, (int, long, type(None))), \
'%s must be an integer or None' % (i,)
self._year = year
self._month = month
self._day = day
self._delta_years = delta_years
self._delta_months = delta_months
self._delta_days = delta_days
@property
def __repr_params__(self):
return (self._year, self._month, self._day,
self._delta_years, self._delta_months, self._delta_days)
def pyson(self):
return {
'__class__': 'Date',
'y': self._year,
'M': self._month,
'd': self._day,
'dy': self._delta_years,
'dM': self._delta_months,
'dd': self._delta_days,
}
def types(self):
return set([datetime.date])
@staticmethod
def eval(dct, context):
return datetime.date.today() + relativedelta(
year=dct['y'],
month=dct['M'],
day=dct['d'],
years=dct['dy'],
months=dct['dM'],
days=dct['dd'],
)
class DateTime(Date):
def __init__(self, year=None, month=None, day=None,
hour=None, minute=None, second=None, microsecond=None,
delta_years=0, delta_months=0, delta_days=0,
delta_hours=0, delta_minutes=0, delta_seconds=0,
delta_microseconds=0, **kwargs):
hour = kwargs.get('h', hour)
minute = kwargs.get('m', minute)
second = kwargs.get('s', second)
microsecond = kwargs.get('ms', microsecond)
delta_hours = kwargs.get('dh', delta_hours)
delta_minutes = kwargs.get('dm', delta_minutes)
delta_seconds = kwargs.get('ds', delta_seconds)
delta_microseconds = kwargs.get('dms', delta_microseconds)
super(DateTime, self).__init__(year=year, month=month, day=day,
delta_years=delta_years, delta_months=delta_months,
delta_days=delta_days, **kwargs)
for i in (hour, minute, second, microsecond,
delta_hours, delta_minutes, delta_seconds, delta_microseconds):
if isinstance(i, PYSON):
assert i.types() == set([int, type(None)]), \
'%s must be an integer or None' % (i,)
else:
assert isinstance(i, (int, long, type(None))), \
'%s must be an integer or None' % (i,)
self._hour = hour
self._minute = minute
self._second = second
self._microsecond = microsecond
self._delta_hours = delta_hours
self._delta_minutes = delta_minutes
self._delta_seconds = delta_seconds
self._delta_microseconds = delta_microseconds
@property
def __repr_params__(self):
date_params = super(DateTime, self).__repr_params__
return (date_params[:3]
+ (self._hour, self._minute, self._second, self._microsecond)
+ date_params[3:]
+ (self._delta_hours, self._delta_minutes, self._delta_seconds,
self._delta_microseconds))
def pyson(self):
res = super(DateTime, self).pyson()
res['__class__'] = 'DateTime'
res['h'] = self._hour
res['m'] = self._minute
res['s'] = self._second
res['ms'] = self._microsecond
res['dh'] = self._delta_hours
res['dm'] = self._delta_minutes
res['ds'] = self._delta_seconds
res['dms'] = self._delta_microseconds
return res
def types(self):
return set([datetime.datetime])
@staticmethod
def eval(dct, context):
return datetime.datetime.now() + relativedelta(
year=dct['y'],
month=dct['M'],
day=dct['d'],
hour=dct['h'],
minute=dct['m'],
second=dct['s'],
microsecond=dct['ms'],
years=dct['dy'],
months=dct['dM'],
days=dct['dd'],
hours=dct['dh'],
minutes=dct['dm'],
seconds=dct['ds'],
microseconds=dct['dms'],
)
class Len(PYSON):
def __init__(self, v):
super(Len, self).__init__()
if isinstance(v, PYSON):
assert v.types().issubset(set([dict, list, basestring])), \
'value must be a dict or a list or a string'
else:
assert isinstance(v, (dict, list, basestring)), \
'value must be a dict or list or a string'
self._value = v
@property
def __repr_params__(self):
return (self._value,)
def pyson(self):
return {
'__class__': 'Len',
'v': self._value,
}
def types(self):
return set([int])
@staticmethod
def eval(dct, context):
return len(dct['v'])
CONTEXT = {
'Eval': Eval,
'Not': Not,
'Bool': Bool,
'And': And,
'Or': Or,
'Equal': Equal,
'Greater': Greater,
'Less': Less,
'If': If,
'Get': Get,
'In': In,
'Date': Date,
'DateTime': DateTime,
'Len': Len,
}
proteus-4.6.1/.drone.yml 0000644 0001750 0001750 00000000701 13235121233 014434 0 ustar ced ced 0000000 0000000 clone:
hg:
image: plugins/hg
pipeline:
tox:
image: ${IMAGE}
commands:
- pip install tox pydot
- tox -e "${TOXENV}"
volumes:
- cache:/root/.cache
matrix:
include:
- IMAGE: python:2.7
TOXENV: py27
- IMAGE: python:3.4
TOXENV: py34
- IMAGE: python:3.5
TOXENV: py35
- IMAGE: python:3.6
TOXENV: py36
proteus-4.6.1/README 0000644 0001750 0001750 00000006705 13235121233 013416 0 ustar ced ced 0000000 0000000 proteus
=======
A library to access Tryton's models like a client.
Installing
----------
See INSTALL
Example of usage
----------------
>>> from proteus import config, Model, Wizard, Report
Configuration
~~~~~~~~~~~~~
Configuration to connect to a sqlite memory database using trytond as module.
>>> config = config.set_trytond('sqlite:///:memory:')
Installing a module
~~~~~~~~~~~~~~~~~~~
Find the module, call the activate button and run the upgrade wizard.
>>> Module = Model.get('ir.module')
>>> party_module, = Module.find([('name', '=', 'party')])
>>> party_module.click('activate')
>>> Wizard('ir.module.activate_upgrade').execute('upgrade')
Creating a party
~~~~~~~~~~~~~~~~
First instanciate a new Party:
>>> Party = Model.get('party.party')
>>> party = Party()
>>> party.id < 0
True
Fill the fields:
>>> party.name = 'ham'
Save the instance into the server:
>>> party.save()
>>> party.name
u'ham'
>>> party.id > 0
True
Setting the language of the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The language on party is a `Many2One` relation field. So it requires to get a
`Model` instance as value.
>>> Lang = Model.get('ir.lang')
>>> en, = Lang.find([('code', '=', 'en')])
>>> party.lang = en
>>> party.save()
>>> party.lang.code
u'en'
Creating an address for the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Addresses are store on party with a `One2Many` field. So the new address just
needs to be appended to the list `addresses`.
>>> address = party.addresses.new(zip='42')
>>> party.save()
>>> party.addresses #doctest: +ELLIPSIS
[proteus.Model.get('party.address')(...)]
Adding category to the party
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Categories are linked to party with a `Many2Many` field.
So first create a category
>>> Category = Model.get('party.category')
>>> category = Category()
>>> category.name = 'spam'
>>> category.save()
Append it to categories of the party
>>> party.categories.append(category)
>>> party.save()
>>> party.categories #doctest: +ELLIPSIS
[proteus.Model.get('party.category')(...)]
Print party label
~~~~~~~~~~~~~~~~~
There is a label report on `Party`.
>>> label = Report('party.label')
The report is executed with a list of records and some extra data.
>>> type_, data, print_, name = label.execute([party], {})
Sorting addresses and register order
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Addresses are ordered by sequence which means they can be stored following a
specific order. The `set_sequence` method stores the current order.
>>> address = party.addresses.new(zip='69')
>>> party.save()
>>> address = party.addresses.new(zip='23')
>>> party.save()
Now changing the order.
>>> reversed_addresses = list(reversed(party.addresses))
>>> while party.addresses:
... _ = party.addresses.pop()
>>> party.addresses.extend(reversed_addresses)
>>> party.addresses.set_sequence()
>>> party.save()
>>> party.addresses == reversed_addresses
True
Support
-------
If you encounter any problems with Tryton, please don't hesitate to ask
questions on the Tryton bug tracker, mailing list, wiki or IRC channel:
http://bugs.tryton.org/
http://groups.tryton.org/
http://wiki.tryton.org/
irc://irc.freenode.net/tryton
License
-------
See LICENSE
Copyright
---------
See COPYRIGHT
For more information please visit the Tryton web site:
http://www.tryton.org/
proteus-4.6.1/setup.cfg 0000644 0001750 0001750 00000000046 13246073656 014370 0 ustar ced ced 0000000 0000000 [egg_info]
tag_build =
tag_date = 0
proteus-4.6.1/INSTALL 0000644 0001750 0001750 00000001514 13235121233 013560 0 ustar ced ced 0000000 0000000 Installing proteus
==================
Prerequisites
-------------
* Python 2.7 or later (http://www.python.org/)
* python-dateutil (http://labix.org/python-dateutil)
* Optional: trytond (http://www.tryton.org/)
* Optional: cdecimal (http://www.bytereef.org/mpdecimal/index.html)
Installation
------------
Once you've downloaded and unpacked the proteus source release, enter the
directory where the archive was unpacked, and run:
python setup.py install
Note that you may need administrator/root privileges for this step, as
this command will by default attempt to install module to the Python
site-packages directory on your system.
For advanced options, please refer to the easy_install and/or the distutils
documentation:
http://setuptools.readthedocs.io/en/latest/easy_install.html
http://docs.python.org/inst/inst.html
proteus-4.6.1/COPYRIGHT 0000644 0001750 0001750 00000001266 13246073655 014046 0 ustar ced ced 0000000 0000000 Copyright (C) 2010-2018 Cédric Krier.
Copyright (C) 2010-2018 B2CK SPRL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
proteus-4.6.1/tox.ini 0000644 0001750 0001750 00000000451 13235121233 014041 0 ustar ced ced 0000000 0000000 [tox]
envlist = py27,py34,py35,py36,pypy
[testenv]
commands = {envpython} setup.py test
deps =
setenv =
TRYTOND_DATABASE_URI={env:TRYTOND_DATBASE_URI:sqlite://}
DB_NAME={env:DB_NAME::memory:}
install_command = pip install --pre --find-links https://trydevpi.tryton.org/ {opts} {packages}