Trop fastidieux de creer un symlink a chaque fichier modifie
-> Copie globale des sources de passerelle
This commit is contained in:
parent
39067003f2
commit
209173d7d4
|
@ -0,0 +1,2 @@
|
|||
[run]
|
||||
omit = */south_migrations/*
|
|
@ -0,0 +1,5 @@
|
|||
*.pyc
|
||||
local_settings.py
|
||||
passerelle.sqlite3
|
||||
media
|
||||
/static
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
|
@ -0,0 +1,12 @@
|
|||
recursive-include passerelle *.html *.mako README
|
||||
recursive-include passerelle/static *
|
||||
recursive-include passerelle/apps/*/static *
|
||||
|
||||
# locales
|
||||
recursive-include passerelle/locale *.po *.mo
|
||||
|
||||
|
||||
include passerelle/apps/orange/orange.pem
|
||||
include LICENSE
|
||||
include MANIFEST.in
|
||||
include VERSION
|
|
@ -0,0 +1,100 @@
|
|||
Passerelle provides an uniform access to multiple data sources and services.
|
||||
|
||||
Quickstart
|
||||
==========
|
||||
|
||||
Setting up an environment (virtualenv)
|
||||
--------------------------------------
|
||||
|
||||
The first thing you'll need is the Python virtualenv package. You probably
|
||||
already have this, but if not, you can install it with:
|
||||
|
||||
$ easy_install -UZ virtualenv
|
||||
|
||||
Once that's done, choose a location for the environment, and create it with the
|
||||
virtualenv command. For our guide, we're going to choose "venv" in the current
|
||||
directory:
|
||||
|
||||
$ virtualenv venv
|
||||
$ source venv/bin/activate
|
||||
|
||||
Install required Python packages:
|
||||
|
||||
$ pip install -r requirements.txt
|
||||
|
||||
Initializing the database (quickstart: sqlite3)
|
||||
-----------------------------------------------
|
||||
|
||||
To create the database, execute the following line:
|
||||
|
||||
$ python manage.py syncdb --migrate
|
||||
|
||||
The new database is created inside `passerelle.sqlite3` in the current
|
||||
directory.
|
||||
|
||||
Running
|
||||
-------
|
||||
|
||||
The command line for starting is:
|
||||
|
||||
$ python manage.py runserver
|
||||
|
||||
Passerelle is available on http://127.0.0.1:8000/
|
||||
|
||||
|
||||
Settings
|
||||
--------
|
||||
|
||||
Default settings are loaded from settings.py, they can be overloaded by a
|
||||
local_settings.py file set in the same directory, or by a file referenced
|
||||
in the PASSERELLE_SETTINGS_FILE environment variable.
|
||||
|
||||
|
||||
Tests
|
||||
-----
|
||||
|
||||
Unit tests are written using py.test, and its pytest-django support library and
|
||||
run using tox.
|
||||
|
||||
tox
|
||||
|
||||
To run a specific test under a specific environment.
|
||||
|
||||
tox -e django17 -- tests/test_csv_datasource.py
|
||||
|
||||
LICENSES
|
||||
========
|
||||
|
||||
Passerelle
|
||||
Copyright (C) 2013-2014 Entr'ouvert <info@entrouvert.com>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under
|
||||
the terms of the GNU Affero 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 Affero General Public License for more
|
||||
details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along
|
||||
with this program (LICENSE file). If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
icons
|
||||
-----
|
||||
|
||||
icon-concerto.svg license:
|
||||
Creative Commons – Attribution (CC BY 3.0) http://creativecommons.org/licenses/by/3.0/us/
|
||||
"Family" designed by Ahmed Elzahra http://www.thenounproject.com/trochilidae/
|
||||
from the Noun Project http://www.thenounproject.com/
|
||||
|
||||
|
||||
Copyright
|
||||
---------
|
||||
|
||||
django-jsonresponse (https://github.com/jjay/django-jsonresponse)
|
||||
# Files: passerelle/utils/jsonresponse.py
|
||||
# Copyright (c) 2012 Yasha Borevich <j.borevich@gmail.com>
|
||||
# Licensed under the BSD license
|
|
@ -0,0 +1,14 @@
|
|||
DEBUG = True
|
||||
|
||||
SECRET_KEY = 'changeme'
|
||||
|
||||
MEDIA_ROOT = 'media'
|
||||
|
||||
STATIC_ROOT = 'collected-static'
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': 'passerelle.sqlite3',
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
Passerelle server for Debian
|
||||
============================
|
||||
|
||||
Create a tenant
|
||||
---------------
|
||||
|
||||
$ passerelle-manage create_tenant foo.passerelle.example.org
|
||||
|
||||
Configure nginx
|
||||
---------------
|
||||
|
||||
1. Copy /usr/share/doc/passerelle/nginx-example.conf to /etc/nginx/sites-available/passerelle.conf:
|
||||
# cp /usr/share/doc/passerelle/nginx-example.conf /etc/nginx/sites-available/passerelle.conf
|
||||
|
||||
2. Edit /etc/nginx/sites-available/passerelle.conf
|
||||
|
||||
3. Enable nginx passerelle site:
|
||||
# ln -s ../sites-available/passerelle.conf /etc/nginx/sites-enabled/
|
||||
|
||||
4. Reload nginx:
|
||||
# service nginx restart
|
|
@ -0,0 +1,5 @@
|
|||
passerelle (0.0-1) unstable; urgency=low
|
||||
|
||||
* Initial release
|
||||
|
||||
-- Jérôme Schneider <jschneider@entrouvert.com> Thu, 13 Jun 2013 12:29:42 +0200
|
|
@ -0,0 +1 @@
|
|||
8
|
|
@ -0,0 +1,41 @@
|
|||
Source: passerelle
|
||||
Section: python
|
||||
Priority: optional
|
||||
Maintainer: Thomas NOËL <tnoel@entrouvert.com>
|
||||
Build-Depends: debhelper (>= 8.0.0),
|
||||
python-django,
|
||||
python-setuptools (>= 0.6b3),
|
||||
python-all (>= 2.6.6-3)
|
||||
Standards-Version: 3.9.6
|
||||
Homepage: https://dev.entrouvert.org/projects/passerelle
|
||||
X-Python-Version: >= 2.7
|
||||
|
||||
Package: python-passerelle
|
||||
Architecture: all
|
||||
Depends: ${python:Depends},
|
||||
${misc:Depends},
|
||||
python-django (>= 1.7),
|
||||
python-gadjo,
|
||||
python-django-model-utils,
|
||||
python-requests,
|
||||
python-setuptools,
|
||||
python-django-jsonfield,
|
||||
python-magic,
|
||||
python-suds,
|
||||
Recommends: python-soappy, python-phpserialize
|
||||
Suggests: python-sqlalchemy, python-mako
|
||||
Description: Uniform access to multiple data sources and services (Python module)
|
||||
|
||||
Package: passerelle
|
||||
Architecture: all
|
||||
Depends: ${misc:Depends}, adduser,
|
||||
python-passerelle (= ${binary:Version}),
|
||||
python-hobo,
|
||||
python-django-tenant-schemas,
|
||||
python-psycopg2,
|
||||
python-memcache,
|
||||
python-django-mellon,
|
||||
gunicorn
|
||||
Recommends: nginx, postgresql, memcached
|
||||
Description: Uniform access to multiple data sources and services
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
Files: debian/*
|
||||
Copyright: 2015 Thomas NOËL <tnoel@entrouvert.com>
|
||||
License: GPL-2+
|
||||
This package 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 2 of the License, or
|
||||
(at your option) any later version.
|
||||
.
|
||||
This package 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 <http://www.gnu.org/licenses/>
|
||||
.
|
||||
On Debian systems, the complete text of the GNU General
|
||||
Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
|
|
@ -0,0 +1,28 @@
|
|||
# This file is sourced by "execfile" from passerelle.settings
|
||||
|
||||
import os
|
||||
|
||||
# Debian defaults
|
||||
DEBUG = False
|
||||
|
||||
PROJECT_NAME = 'passerelle'
|
||||
|
||||
# SAML2 authentication
|
||||
INSTALLED_APPS += ('mellon',)
|
||||
|
||||
#
|
||||
# hobotization (multitenant)
|
||||
#
|
||||
execfile('/usr/lib/hobo/debian_config_common.py')
|
||||
|
||||
# disable django-mellon autologin
|
||||
MELLON_OPENED_SESSION_COOKIE_NAME = None
|
||||
|
||||
# suds logs are buggy
|
||||
LOGGING['loggers']['suds'] = {
|
||||
'level': 'ERROR',
|
||||
'handlers': ['mail_admins', 'sentry'],
|
||||
'propagate': True,
|
||||
}
|
||||
|
||||
execfile('/etc/%s/settings.py' % PROJECT_NAME)
|
|
@ -0,0 +1,39 @@
|
|||
server {
|
||||
listen 443;
|
||||
server_name *.passerelle.example.org;
|
||||
|
||||
ssl on;
|
||||
ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
|
||||
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
|
||||
|
||||
access_log /var/log/nginx/passerelle.example.org-access.log combined;
|
||||
error_log /var/log/nginx/passerelle.example.org-error.log;
|
||||
|
||||
location ~ ^/static/(.+)$ {
|
||||
root /;
|
||||
try_files /var/lib/passerelle/tenants/$host/static/$1
|
||||
/var/lib/passerelle/collectstatic/$1
|
||||
=404;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://unix:/run/passerelle/passerelle.sock;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-SSL on;
|
||||
proxy_set_header X-Forwarded-Protocol ssl;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name *.passerelle.example.org;
|
||||
|
||||
access_log /var/log/nginx/passerelle.example.org-access.log combined;
|
||||
error_log /var/log/nginx/passerelle.example.org-error.log;
|
||||
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
#!/bin/sh
|
||||
|
||||
NAME=passerelle
|
||||
MANAGE="/usr/lib/passerelle/manage.py"
|
||||
|
||||
# load Debian default configuration
|
||||
export PASSERELLE_SETTINGS_FILE=/usr/lib/$NAME/debian_config.py
|
||||
|
||||
# check user
|
||||
if test x$1 = x"--forceuser"
|
||||
then
|
||||
shift
|
||||
elif test $(id -un) != "$NAME"
|
||||
then
|
||||
echo "error: must use $0 with user ${NAME}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if test $# -eq 0
|
||||
then
|
||||
python ${MANAGE} help
|
||||
exit 1
|
||||
fi
|
||||
|
||||
python ${MANAGE} "$@"
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
MAILTO=root
|
||||
|
||||
0 2 * * * passerelle /usr/bin/passerelle-manage tenant_command update_streets --all-tenants
|
|
@ -0,0 +1,5 @@
|
|||
/etc/passerelle
|
||||
/usr/lib/passerelle
|
||||
/var/lib/passerelle/collectstatic
|
||||
/var/lib/passerelle/tenants
|
||||
/var/log/passerelle
|
|
@ -0,0 +1,2 @@
|
|||
debian/nginx-example.conf
|
||||
debian/README.Debian
|
|
@ -0,0 +1,194 @@
|
|||
#!/bin/sh -e
|
||||
### BEGIN INIT INFO
|
||||
# Provides: passerelle
|
||||
# Required-Start: $network $local_fs $remote_fs $syslog
|
||||
# Required-Stop: $network $local_fs $remote_fs $syslog
|
||||
# Should-Start: postgresql
|
||||
# Should-Stop: postgresql
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: Passerelle server
|
||||
# Description: Passerelle provides an uniform access to multiple data sources and services.
|
||||
### END INIT INFO
|
||||
|
||||
# Author: Jérôme Schneider <jschneider@entrouvert.com>
|
||||
|
||||
PATH=/sbin:/usr/sbin:/bin:/usr/bin
|
||||
DESC=Passerelle
|
||||
NAME=passerelle
|
||||
DAEMON=/usr/bin/gunicorn
|
||||
RUN_DIR=/run/$NAME
|
||||
PIDFILE=$RUN_DIR/$NAME.pid
|
||||
LOG_DIR=/var/log/$NAME
|
||||
SCRIPTNAME=/etc/init.d/$NAME
|
||||
BIND=unix:$RUN_DIR/$NAME.sock
|
||||
WORKERS=5
|
||||
TIMEOUT=30
|
||||
|
||||
PASSERELLE_SETTINGS_FILE=/usr/lib/$NAME/debian_config.py
|
||||
MANAGE_SCRIPT="/usr/bin/$NAME-manage"
|
||||
|
||||
USER=$NAME
|
||||
GROUP=$NAME
|
||||
|
||||
# Exit if the package is not installed
|
||||
[ -x $DAEMON ] || exit 0
|
||||
|
||||
# Read configuration variable file if it is present
|
||||
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
|
||||
|
||||
DAEMON_ARGS=${DAEMON_ARGS:-"--pid $PIDFILE \
|
||||
--user $USER --group $GROUP \
|
||||
--daemon \
|
||||
--access-logfile $LOG_DIR/gunicorn-access.log \
|
||||
--log-file $LOG_DIR/gunicorn-error.log \
|
||||
--bind=$BIND \
|
||||
--workers=$WORKERS \
|
||||
--worker-class=sync \
|
||||
--timeout=$TIMEOUT \
|
||||
--name $NAME \
|
||||
$NAME.wsgi:application"}
|
||||
|
||||
# Load the VERBOSE setting and other rcS variables
|
||||
. /lib/init/vars.sh
|
||||
|
||||
# Define LSB log_* functions.
|
||||
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
# Create /run directory
|
||||
if [ ! -d $RUN_DIR ]; then
|
||||
install -d -m 755 -o $USER -g $GROUP $RUN_DIR
|
||||
fi
|
||||
|
||||
# environment for wsgi
|
||||
export PASSERELLE_SETTINGS_FILE
|
||||
|
||||
#
|
||||
# Function that starts the daemon/service
|
||||
#
|
||||
do_start()
|
||||
{
|
||||
# Return
|
||||
# 0 if daemon has been started
|
||||
# 1 if daemon was already running
|
||||
# 2 if daemon could not be started
|
||||
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
|
||||
|| return 1
|
||||
start-stop-daemon --start --quiet --exec $DAEMON -- \
|
||||
$DAEMON_ARGS \
|
||||
|| return 2
|
||||
}
|
||||
|
||||
#
|
||||
# Function that stops the daemon/service
|
||||
#
|
||||
do_stop()
|
||||
{
|
||||
# Return
|
||||
# 0 if daemon has been stopped
|
||||
# 1 if daemon was already stopped
|
||||
# 2 if daemon could not be stopped
|
||||
# other if a failure occurred
|
||||
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE
|
||||
RETVAL="$?"
|
||||
[ "$RETVAL" = 2 ] && return 2
|
||||
# Wait for children to finish too if this is a daemon that forks
|
||||
# and if the daemon is only ever run from this initscript.
|
||||
# If the above conditions are not satisfied then add some other code
|
||||
# that waits for the process to drop all resources that could be
|
||||
# needed by services started subsequently. A last resort is to
|
||||
# sleep for some time.
|
||||
start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
|
||||
[ "$?" = 2 ] && return 2
|
||||
# Many daemons don't delete their pidfiles when they exit.
|
||||
rm -f $PIDFILE
|
||||
return "$RETVAL"
|
||||
}
|
||||
|
||||
#
|
||||
# Function that sends a SIGHUP to the daemon/service
|
||||
#
|
||||
do_reload() {
|
||||
#
|
||||
# If the daemon can reload its configuration without
|
||||
# restarting (for example, when it is sent a SIGHUP),
|
||||
# then implement that here.
|
||||
#
|
||||
start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name `basename $DAEMON`
|
||||
return 0
|
||||
}
|
||||
|
||||
do_migrate() {
|
||||
log_action_msg "Applying new migrations .."
|
||||
su $USER -s /bin/sh -p -c "$MANAGE_SCRIPT migrate_schemas --noinput"
|
||||
log_action_msg ".. done"
|
||||
}
|
||||
|
||||
do_collectstatic() {
|
||||
log_action_msg "Collect static files.."
|
||||
su $USER -s /bin/sh -p -c "$MANAGE_SCRIPT collectstatic --noinput"
|
||||
log_action_msg ".. done"
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
log_daemon_msg "Starting $DESC " "$NAME"
|
||||
do_migrate
|
||||
do_collectstatic
|
||||
do_start
|
||||
case "$?" in
|
||||
0|1) log_end_msg 0 ;;
|
||||
2) log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
stop)
|
||||
log_daemon_msg "Stopping $DESC" "$NAME"
|
||||
do_stop
|
||||
case "$?" in
|
||||
0|1) log_end_msg 0 ;;
|
||||
2) log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
status)
|
||||
status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
|
||||
;;
|
||||
reload|force-reload)
|
||||
#
|
||||
# If do_reload() is not implemented then leave this commented out
|
||||
# and leave 'force-reload' as an alias for 'restart'.
|
||||
#
|
||||
log_daemon_msg "Reloading $DESC" "$NAME"
|
||||
do_reload
|
||||
log_end_msg $?
|
||||
;;
|
||||
restart|force-reload)
|
||||
#
|
||||
# If the "reload" option is implemented then remove the
|
||||
# 'force-reload' alias
|
||||
#
|
||||
log_daemon_msg "Restarting $DESC" "$NAME"
|
||||
do_stop
|
||||
case "$?" in
|
||||
0|1)
|
||||
do_migrate
|
||||
do_collectstatic
|
||||
do_start
|
||||
case "$?" in
|
||||
0) log_end_msg 0 ;;
|
||||
1) log_end_msg 1 ;; # Old process is still running
|
||||
*) log_end_msg 1 ;; # Failed to start
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
# Failed to stop
|
||||
log_end_msg 1
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $SCRIPTNAME {start|stop|status|restart|reload|force-reload}" >&2
|
||||
exit 3
|
||||
;;
|
||||
esac
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
debian/passerelle-manage /usr/bin
|
||||
debian/debian_config.py /usr/lib/passerelle
|
||||
debian/settings.py /etc/passerelle
|
|
@ -0,0 +1,50 @@
|
|||
#! /bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
NAME="passerelle"
|
||||
USER=$NAME
|
||||
GROUP=$NAME
|
||||
CONFIG_DIR="/etc/$NAME"
|
||||
MANAGE_SCRIPT="/usr/bin/$NAME-manage"
|
||||
|
||||
case "$1" in
|
||||
configure)
|
||||
|
||||
# make sure the administrative user exists
|
||||
if ! getent passwd $USER >/dev/null; then
|
||||
adduser --disabled-password --quiet --system \
|
||||
--no-create-home --home /var/lib/$NAME \
|
||||
--gecos "Passerelle user" --group $USER
|
||||
fi
|
||||
# ensure dirs ownership
|
||||
chown $USER:$GROUP /var/log/$NAME
|
||||
chown $USER:$GROUP /var/lib/$NAME/collectstatic
|
||||
chown $USER:$GROUP /var/lib/$NAME/tenants
|
||||
# create a secret file
|
||||
SECRET_FILE=$CONFIG_DIR/secret
|
||||
if [ ! -f $SECRET_FILE ]; then
|
||||
echo -n "Generating Django secret..." >&2
|
||||
cat /dev/urandom | tr -dc [:alnum:]-_\!\%\^:\; | head -c70 > $SECRET_FILE
|
||||
chown root:$GROUP $SECRET_FILE
|
||||
chmod 0440 $SECRET_FILE
|
||||
echo "done" >&2
|
||||
fi
|
||||
;;
|
||||
|
||||
triggered)
|
||||
su -s /bin/sh -c "$MANAGE_SCRIPT hobo_deploy --redeploy" $USER
|
||||
;;
|
||||
|
||||
abort-upgrade|abort-remove|abort-deconfigure)
|
||||
;;
|
||||
*)
|
||||
echo "postinst called with unknown argument \`$1'" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
#DEBHELPER#
|
||||
|
||||
exit 0
|
||||
|
|
@ -0,0 +1 @@
|
|||
interest-noawait hobo-redeploy
|
|
@ -0,0 +1,2 @@
|
|||
jsonfield python-django-jsonfield
|
||||
django-jsonresponse python-django-jsonresponse
|
|
@ -0,0 +1 @@
|
|||
/usr/lib/passerelle
|
|
@ -0,0 +1,2 @@
|
|||
README
|
||||
LICENSE
|
|
@ -0,0 +1,2 @@
|
|||
usr/bin/manage.py /usr/lib/passerelle
|
||||
usr/lib/python2*/*-packages
|
|
@ -0,0 +1,8 @@
|
|||
#!/usr/bin/make -f
|
||||
# -*- makefile -*-
|
||||
|
||||
# Uncomment this to turn on verbose mode.
|
||||
#export DH_VERBOSE=1
|
||||
|
||||
%:
|
||||
dh $@ --with python2
|
|
@ -0,0 +1,55 @@
|
|||
# Configuration for passerelle.
|
||||
# You can override Passerelle default settings here
|
||||
|
||||
# Passerelle is a Django application: for the full list of settings and their
|
||||
# values, see https://docs.djangoproject.com/en/1.7/ref/settings/
|
||||
# For more information on settings see
|
||||
# https://docs.djangoproject.com/en/1.7/topics/settings/
|
||||
|
||||
# WARNING! Quick-start development settings unsuitable for production!
|
||||
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
|
||||
|
||||
# This file is sourced by "execfile" from /usr/lib/passerelle/debian_config.py
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
#DEBUG = False
|
||||
#TEMPLATE_DEBUG = False
|
||||
|
||||
#ADMINS = (
|
||||
# ('User 1', 'poulpe@example.org'),
|
||||
# ('User 2', 'janitor@example.net'),
|
||||
#)
|
||||
|
||||
# ALLOWED_HOSTS must be correct in production!
|
||||
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
||||
# If a tenant doesn't exist, the tenant middleware raise a 404 error. If you
|
||||
# prefer to redirect to a specific site, use:
|
||||
# TENANT_NOT_FOUND_REDIRECT_URL = 'http://www.example.net/'
|
||||
|
||||
# Database
|
||||
# Warning: don't change ENGINE, it must be 'tenant_schemas.postgresql_backend'
|
||||
#DATABASES['default']['NAME'] = 'passerelle'
|
||||
#DATABASES['default']['USER'] = 'passerelle'
|
||||
#DATABASES['default']['PASSWORD'] = '******'
|
||||
#DATABASES['default']['HOST'] = 'localhost'
|
||||
#DATABASES['default']['PORT'] = '5432'
|
||||
|
||||
LANGUAGE_CODE = 'fr-fr'
|
||||
TIME_ZONE = 'Europe/Paris'
|
||||
|
||||
# Email configuration
|
||||
#EMAIL_SUBJECT_PREFIX = '[passerelle] '
|
||||
#SERVER_EMAIL = 'root@passerelle.example.org'
|
||||
#DEFAULT_FROM_EMAIL = 'webmaster@passerelle.example.org'
|
||||
|
||||
# SMTP configuration
|
||||
#EMAIL_HOST = 'localhost'
|
||||
#EMAIL_HOST_USER = ''
|
||||
#EMAIL_HOST_PASSWORD = ''
|
||||
#EMAIL_PORT = 25
|
||||
|
||||
# HTTPS
|
||||
#CSRF_COOKIE_SECURE = True
|
||||
#SESSION_COOKIE_SECURE = True
|
|
@ -0,0 +1,22 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Get venv site-packages path
|
||||
DSTDIR=`python -c 'from distutils.sysconfig import get_python_lib; print(get_python_lib())'`
|
||||
|
||||
# Get not venv site-packages path
|
||||
# Remove first path (assuming that is the venv path)
|
||||
NONPATH=`echo $PATH | sed 's/^[^:]*://'`
|
||||
if ! /usr/bin/python -c 'import magic' >/dev/null 2>&1; then
|
||||
echo magic package is not installed
|
||||
exit 1
|
||||
fi
|
||||
SRCDIR=`/usr/bin/python -c 'from distutils.sysconfig import get_python_lib; print(get_python_lib())'`
|
||||
|
||||
# Clean up
|
||||
rm -f $DSTDIR/magic.py
|
||||
|
||||
# Link
|
||||
ln -sv $SRCDIR/magic.py $DSTDIR
|
||||
|
||||
exit 0
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
rm -f coverage.xml
|
||||
rm -f test_results.xml
|
||||
|
||||
pip install --upgrade tox
|
||||
tox -r
|
|
@ -0,0 +1,10 @@
|
|||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "passerelle.settings")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
|
@ -0,0 +1,6 @@
|
|||
import sys
|
||||
import os.path
|
||||
|
||||
apps_dir = os.path.join(os.path.dirname(__file__), 'apps')
|
||||
if apps_dir not in sys.path:
|
||||
sys.path.append(apps_dir)
|
|
@ -0,0 +1,42 @@
|
|||
import urllib
|
||||
import bz2
|
||||
import json
|
||||
import logging
|
||||
|
||||
from django.utils import timezone
|
||||
from django.core.management.base import BaseCommand
|
||||
from ...models import StreetModel, BaseAdresse
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = _('Retrieve streets update saved and apply them. No args needed.')
|
||||
|
||||
def launch_update(self, zipcode, start_update):
|
||||
file_zip = urllib.urlretrieve('http://bano.openstreetmap.fr/BAN_odbl/BAN_odbl_{}-json.bz2'.format(zipcode[:2]))
|
||||
file_unzip = bz2.BZ2File(file_zip[0])
|
||||
|
||||
zip_lines = file_unzip.readlines()
|
||||
|
||||
for line in zip_lines:
|
||||
street_info = json.loads(line)
|
||||
if street_info['type'] == 'street' and street_info['postcode'].startswith(zipcode):
|
||||
street = StreetModel.objects.get_or_create(citycode=street_info['citycode'],
|
||||
name=street_info['name'])
|
||||
street[0].city = street_info['city']
|
||||
street[0].name = street_info['name'][:149]
|
||||
street[0].zipcode = street_info['postcode']
|
||||
street[0].type = street_info['type']
|
||||
street[0].citycode = street_info['citycode']
|
||||
street[0].save()
|
||||
|
||||
StreetModel.objects.filter(last_update__lt=start_update, zipcode__startswith=zipcode).delete()
|
||||
|
||||
def handle(self, *args, **options):
|
||||
logging.basicConfig()
|
||||
logger = logging.getLogger(__name__)
|
||||
for base_adr in BaseAdresse.objects.exclude(zipcode=''):
|
||||
try:
|
||||
self.launch_update(base_adr.zipcode, timezone.now())
|
||||
except Exception as e:
|
||||
logger.exception(u'error while updating base_adresse %s: %s', base_adr.title, e)
|
|
@ -0,0 +1,29 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='BaseAddresse',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('slug', models.SlugField()),
|
||||
('description', models.TextField()),
|
||||
('service_url', models.CharField(help_text='Base Adresse Web Service URL', max_length=128, verbose_name='Service URL')),
|
||||
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Base Adresse Web Service',
|
||||
},
|
||||
bases=(models.Model,),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='baseaddresse',
|
||||
name='service_url',
|
||||
field=models.CharField(default=b'https://api-adresse.data.gouv.fr/', help_text='Base Adresse Web Service URL', max_length=128, verbose_name='Service URL'),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0002_auto_20150705_0330'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='baseaddresse',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Debug Enabled', blank=True, choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0003_baseaddresse_log_level'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='baseaddresse',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0004_auto_20160316_0910'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='baseaddresse',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,15 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0005_auto_20160407_0456'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RenameModel('BaseAddresse', 'BaseAdresse')
|
||||
]
|
|
@ -0,0 +1,40 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0006_rename_model'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='StreetModel',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('city', models.CharField(max_length=100, verbose_name='City')),
|
||||
('name', models.CharField(max_length=150, verbose_name='Street name')),
|
||||
('zipcode', models.CharField(max_length=5, verbose_name='Postal code')),
|
||||
('type', models.CharField(max_length=30, verbose_name='Street type')),
|
||||
('citycode', models.CharField(max_length=5, verbose_name='City Code')),
|
||||
('last_update', models.DateTimeField(null=True, verbose_name='Last update')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UpdateStreetModel',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('zipcode', models.CharField(max_length=5, verbose_name='Postal code')),
|
||||
('start_time', models.DateTimeField(null=True, verbose_name='Start of update')),
|
||||
('end_time', models.DateTimeField(null=True, verbose_name='End of update')),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='baseadresse',
|
||||
name='zipcode',
|
||||
field=models.CharField(help_text='Postal code to get the streets from.', max_length=5, verbose_name='Postal code to get streets', blank=True),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,17 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0007_auto_20160729_1540'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.DeleteModel(
|
||||
name='UpdateStreetModel',
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0008_delete_updatestreetmodel'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='streetmodel',
|
||||
name='unaccent_name',
|
||||
field=models.CharField(max_length=150, null=True, verbose_name='Street name ascii char'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0009_streetmodel_simple_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='streetmodel',
|
||||
name='last_update',
|
||||
field=models.DateTimeField(auto_now=True, verbose_name='Last update', null=True),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,18 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base_adresse', '0010_auto_20160914_0826'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='streetmodel',
|
||||
options={'ordering': ['unaccent_name', 'name']},
|
||||
),
|
||||
]
|
|
@ -0,0 +1,140 @@
|
|||
import urlparse
|
||||
import unicodedata
|
||||
|
||||
from django.db import models
|
||||
from django.utils.http import urlencode
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils import timezone
|
||||
|
||||
from passerelle.base.models import BaseResource
|
||||
from passerelle.utils.api import endpoint
|
||||
|
||||
|
||||
class BaseAdresse(BaseResource):
|
||||
service_url = models.CharField(
|
||||
max_length=128, blank=False,
|
||||
default='https://api-adresse.data.gouv.fr/',
|
||||
verbose_name=_('Service URL'),
|
||||
help_text=_('Base Adresse Web Service URL'))
|
||||
|
||||
category = _('Geographic information system')
|
||||
|
||||
zipcode = models.CharField(max_length=5, blank=True,
|
||||
verbose_name=_('Postal code to get streets'),
|
||||
help_text=_('Postal code to get the streets from.'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('Base Adresse Web Service')
|
||||
|
||||
@classmethod
|
||||
def get_icon_class(cls):
|
||||
return 'gis'
|
||||
|
||||
@endpoint(pattern='(?P<q>.+)?$')
|
||||
def search(self, request, q, zipcode='', **kwargs):
|
||||
if kwargs.get('format', 'json') != 'json':
|
||||
raise NotImplementedError()
|
||||
|
||||
scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.service_url)
|
||||
path = '/search/'
|
||||
query = urlencode({
|
||||
'q': q, 'limit': 1,
|
||||
'postcode': zipcode,
|
||||
})
|
||||
|
||||
url = urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
|
||||
|
||||
result_response = self.requests.get(url)
|
||||
result = []
|
||||
|
||||
for feature in result_response.json().get('features'):
|
||||
if not feature['geometry']['type'] == 'Point':
|
||||
continue # skip unknown
|
||||
result.append({
|
||||
'lon': str(feature['geometry']['coordinates'][0]),
|
||||
'lat': str(feature['geometry']['coordinates'][1]),
|
||||
'display_name': feature['properties']['label'],
|
||||
})
|
||||
break
|
||||
|
||||
return result
|
||||
|
||||
@endpoint()
|
||||
def reverse(self, request, lat, lon, **kwargs):
|
||||
if kwargs.get('format', 'json') != 'json':
|
||||
raise NotImplementedError()
|
||||
|
||||
scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.service_url)
|
||||
path = '/reverse/'
|
||||
query = urlencode({'lat': lat, 'lon': lon})
|
||||
url = urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
|
||||
|
||||
result_response = self.requests.get(url)
|
||||
result = None
|
||||
|
||||
for feature in result_response.json().get('features'):
|
||||
if not feature['geometry']['type'] == 'Point':
|
||||
continue # skip unknown
|
||||
result = {}
|
||||
result['lon'] = str(feature['geometry']['coordinates'][0])
|
||||
result['lat'] = str(feature['geometry']['coordinates'][1])
|
||||
result['address'] = {'country': 'France'}
|
||||
for prop in feature['properties']:
|
||||
if prop in ('city', 'postcode'):
|
||||
result['address'][prop] = feature['properties'][prop]
|
||||
elif prop == 'housenumber':
|
||||
result['address']['house_number'] = feature['properties'][prop]
|
||||
elif prop == 'label':
|
||||
result['display_name'] = feature['properties'][prop]
|
||||
elif prop == 'name':
|
||||
house_number = feature['properties'].get('housenumber')
|
||||
value = feature['properties'][prop]
|
||||
if house_number and value.startswith(house_number):
|
||||
value = value[len(house_number):].strip()
|
||||
result['address']['road'] = value
|
||||
return result
|
||||
|
||||
@endpoint(serializer_type='json-api')
|
||||
def streets(self, request, zipcode=None, q=None, page_limit=None):
|
||||
result = []
|
||||
streets = StreetModel.objects.all()
|
||||
if q:
|
||||
unaccented_q = unicodedata.normalize('NFKD', q).encode('ascii', 'ignore').lower()
|
||||
streets = streets.filter(unaccent_name__icontains=unaccented_q)
|
||||
|
||||
if zipcode:
|
||||
streets = streets.filter(zipcode__startswith=zipcode)
|
||||
|
||||
if page_limit:
|
||||
streets = streets[:page_limit]
|
||||
|
||||
for street in streets:
|
||||
result.append({'id': street.id,
|
||||
'text': street.name,
|
||||
'type': street.type,
|
||||
'city': street.city,
|
||||
'citycode': street.citycode,
|
||||
'zipcode': street.zipcode})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class StreetModel(models.Model):
|
||||
|
||||
city = models.CharField(_('City'), max_length=100)
|
||||
name = models.CharField(_('Street name'), max_length=150)
|
||||
unaccent_name = models.CharField(_('Street name ascii char'), max_length=150, null=True)
|
||||
zipcode = models.CharField(_('Postal code'), max_length=5)
|
||||
type = models.CharField(_('Street type'), max_length=30)
|
||||
citycode = models.CharField(_('City Code'), max_length=5)
|
||||
last_update = models.DateTimeField(_('Last update'), null=True, auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['unaccent_name', 'name']
|
||||
|
||||
def __unicode__(self):
|
||||
return unicode(self.name)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
self.unaccent_name = unicodedata.normalize('NFKD', self.name).encode('ascii', 'ignore')
|
||||
super(StreetModel, self).save(*args, **kwargs)
|
|
@ -0,0 +1,27 @@
|
|||
{% extends "passerelle/manage/service_view.html" %}
|
||||
{% load i18n passerelle %}
|
||||
|
||||
{% block endpoints %}
|
||||
<p>
|
||||
{% blocktrans %}
|
||||
The API is a partial view of <a href="http://wiki.openstreetmap.org/wiki/Nominatim">Nominatim</a>
|
||||
own API; it currently doesn't support all parameters and is limited to the JSON
|
||||
format.
|
||||
{% endblocktrans %}
|
||||
</p>
|
||||
|
||||
<ul>
|
||||
<li>{% trans 'Geocoding:' %} <a href="search?q=169 rue du chateau, paris&format=json"
|
||||
>{{ site_base_uri }}{{ object.get_absolute_url }}search</a>?q=<i>q</i>&format=json</li>
|
||||
<li>{% trans 'Reverse geocoding:' %} <a href="reverse?lat=48.833708&lon=2.323349&format=json"
|
||||
>{{ site_base_uri }}{{ object.get_absolute_url }}reverse</a>?lat=<i>lat</i>&lon=<i>lon</i>&format=json</li>
|
||||
<li>{% trans 'Streets from zipcode:' %} <a href="streets?zipcode={{object.zipcode}}&format=json"
|
||||
>{{ site_base_uri }}{{ object.get_absolute_url }}streets</a>?zipcode=<i>zipcode</i>&format=json</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
||||
{% block security %}
|
||||
<p>
|
||||
{% trans 'Accessing the listings is open.' %}
|
||||
</p>
|
||||
{% endblock %}
|
|
@ -0,0 +1,9 @@
|
|||
from django.contrib import admin
|
||||
|
||||
from models import Bdp
|
||||
|
||||
|
||||
class BdpAdmin(admin.ModelAdmin):
|
||||
prepopulated_fields = {'slug': ('title',)}
|
||||
|
||||
admin.site.register(Bdp, BdpAdmin)
|
|
@ -0,0 +1,33 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Bdp',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('slug', models.SlugField()),
|
||||
('description', models.TextField()),
|
||||
('service_url', models.CharField(help_text='BDP Web Service URL', max_length=128, verbose_name='Service URL')),
|
||||
('username', models.CharField(max_length=128, verbose_name='Username', blank=True)),
|
||||
('password', models.CharField(max_length=128, verbose_name='Password', blank=True)),
|
||||
('verify_cert', models.BooleanField(default=True, verbose_name='Check HTTPS Certificate validity')),
|
||||
('keystore', models.FileField(help_text='Certificate and private key in PEM format', upload_to=b'bdp', null=True, verbose_name='Keystore', blank=True)),
|
||||
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'BDP Web Service',
|
||||
},
|
||||
bases=(models.Model,),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('bdp', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='bdp',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Debug Enabled', blank=True, choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('bdp', '0002_bdp_log_level'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='bdp',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('bdp', '0003_auto_20160316_0910'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='bdp',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,66 @@
|
|||
import json
|
||||
import requests
|
||||
from requests.auth import HTTPBasicAuth
|
||||
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.db import models
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from passerelle.base.models import BaseResource
|
||||
|
||||
class Bdp(BaseResource):
|
||||
service_url = models.CharField(max_length=128, blank=False,
|
||||
verbose_name=_('Service URL'),
|
||||
help_text=_('BDP Web Service URL'))
|
||||
username = models.CharField(max_length=128, blank=True,
|
||||
verbose_name=_('Username'))
|
||||
password = models.CharField(max_length=128, blank=True,
|
||||
verbose_name=_('Password'))
|
||||
verify_cert = models.BooleanField(default=True,
|
||||
verbose_name=_('Check HTTPS Certificate validity'))
|
||||
keystore = models.FileField(upload_to='bdp',
|
||||
blank=True, null=True,
|
||||
verbose_name=_('Keystore'),
|
||||
help_text=_('Certificate and private key in PEM format'))
|
||||
|
||||
category = _('Business Process Connectors')
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('BDP Web Service')
|
||||
|
||||
@classmethod
|
||||
def get_icon_class(cls):
|
||||
return 'bdp'
|
||||
|
||||
def requests_options(self):
|
||||
options = {}
|
||||
if self.keystore:
|
||||
options['cert'] = (self.keystore.path, self.keystore.path)
|
||||
if not self.verify_cert:
|
||||
options['verify'] = False
|
||||
if self.username:
|
||||
options['auth'] = HTTPBasicAuth(self.username, self.password)
|
||||
return options
|
||||
|
||||
def get_api(self, endpoint, **params):
|
||||
options = self.requests_options()
|
||||
return requests.get(self.service_url + '/api/' + endpoint,
|
||||
params=params, **options).json()
|
||||
|
||||
def post_api(self, endpoint, obj):
|
||||
data = json.dumps(obj)
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
options = self.requests_options()
|
||||
request = requests.post(
|
||||
self.service_url + '/api/' + endpoint,
|
||||
data=data, headers=headers, **options)
|
||||
result = {
|
||||
'status_code': request.status_code,
|
||||
'x_request_id': request.headers.get('x-request-id'),
|
||||
'x_status_reason': request.headers.get('x-status-reason'),
|
||||
}
|
||||
try:
|
||||
result.update(request.json())
|
||||
except ValueError:
|
||||
result['content'] = request.text
|
||||
return result
|
|
@ -0,0 +1,46 @@
|
|||
{% extends "passerelle/manage/service_view.html" %}
|
||||
{% load i18n passerelle %}
|
||||
|
||||
{% block description %}
|
||||
<p>
|
||||
Service URL : {{ object.service_url }}
|
||||
</p>
|
||||
{% endblock %}
|
||||
|
||||
{% block endpoints %}
|
||||
<ul>
|
||||
<li>{% trans 'Listing resources:' %} <a
|
||||
>{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='resources' %}</a> (GET)</li>
|
||||
<li>{% trans 'Creating a new user:' %} <a
|
||||
>{{ site_base_uri }}{% url 'bdp-post-adherent' slug=object.slug %}</a> (POST)</li>
|
||||
</ul>
|
||||
|
||||
<div>
|
||||
<h3>{% trans 'Examples' %}</h3>
|
||||
<ul>
|
||||
<li>{% trans 'Libraries:' %} <a
|
||||
href="{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='bibliotheques' %}"
|
||||
>{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='bibliotheques' %}</a>
|
||||
</li>
|
||||
<li>{% trans 'Libraries with a text label:' %} <a
|
||||
href="{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='bibliotheques' %}?text_key=nom"
|
||||
>{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='bibliotheques' %}?text_key=nom</a>
|
||||
</li>
|
||||
<li>{% trans 'Members:' %} <a
|
||||
href="{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='adherents' %}"
|
||||
>{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='adherents' %}</a>
|
||||
</li>
|
||||
<li>{% trans 'Filtered Members:' %} <a
|
||||
href="{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='adherents' %}?filter[0][field]=email&filter[0][operator]=eq&filter[0][value]=login@example.net"
|
||||
>{{ site_base_uri }}{% url 'bdp-resources' slug=object.slug resources='adherents' %}?filter[0][field]=email&filter[0][operator]=eq&filter[0][value]=login@example.net</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block security %}
|
||||
<p>
|
||||
{% trans 'Accessing is limited to the following API users:' %}
|
||||
</p>
|
||||
{% access_rights_table resource=object permission='can_access' %}
|
||||
{% endblock %}
|
|
@ -0,0 +1,9 @@
|
|||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.conf.urls import patterns, url
|
||||
from views import *
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^(?P<slug>[\w,-]+)/$', BdpDetailView.as_view(), name='bdp-view'),
|
||||
url(r'^(?P<slug>[\w,-]+)/(?P<resources>[\w,-]+)/$', ResourcesView.as_view(), name='bdp-resources'),
|
||||
url(r'^(?P<slug>[\w,-]+)/post/adherent/$', csrf_exempt(PostAdherentView.as_view()), name='bdp-post-adherent'),
|
||||
)
|
|
@ -0,0 +1,69 @@
|
|||
import json
|
||||
|
||||
from django.http import Http404
|
||||
from django.views.generic.base import View
|
||||
from django.views.generic.detail import SingleObjectMixin, DetailView
|
||||
|
||||
from passerelle import utils
|
||||
|
||||
from .models import Bdp
|
||||
|
||||
# See documentation:
|
||||
# https://dev.entrouvert.org/projects/bdp/wiki/WebServices
|
||||
|
||||
|
||||
class ResourcesView(View, SingleObjectMixin):
|
||||
model = Bdp
|
||||
|
||||
@utils.protected_api('can_access')
|
||||
@utils.to_json('api')
|
||||
def get(self, request, *args, **kwargs):
|
||||
text_key = request.GET.get('text_key')
|
||||
id_key = request.GET.get('id_key')
|
||||
resources = self.get_object().get_api(kwargs['resources'], **(request.GET))
|
||||
for r in resources:
|
||||
if id_key:
|
||||
r['id'] = r[id_key]
|
||||
r['id'] = '%s' % r['id']
|
||||
if text_key:
|
||||
r['text'] = r[text_key]
|
||||
elif 'text' not in r:
|
||||
r['text'] = r['id']
|
||||
return resources
|
||||
|
||||
|
||||
class PostAdherentView(View, SingleObjectMixin):
|
||||
model = Bdp
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
raise Http404
|
||||
|
||||
@utils.protected_api('can_access')
|
||||
@utils.to_json('api')
|
||||
def post(self, request, *args, **kwargs):
|
||||
data = json.loads(request.body) # JSON w.c.s. formdata
|
||||
date_de_naissance = data['fields'].get('date_de_naissance')
|
||||
# force 1973-04-18T00:00:00Z
|
||||
date_de_naissance = date_de_naissance[:10] + 'T00:00:00Z'
|
||||
abonnements = data['fields'].get('abonnements_raw') or \
|
||||
data['fields'].get('abonnements_raw') or \
|
||||
request.GET.get('abonnements')
|
||||
bibliotheque_id = data['fields'].get('bibliotheque_raw') or \
|
||||
data['fields'].get('bibliotheque') or \
|
||||
request.GET.get('bibliotheque')
|
||||
adherent = {
|
||||
'nom': data['fields'].get('nom'),
|
||||
'prenom': data['fields'].get('prenom'),
|
||||
'email': data['fields'].get('courriel'),
|
||||
'hashpass': data['fields'].get('mot_de_passe').get('cleartext'),
|
||||
'dateNaissance': date_de_naissance,
|
||||
'actif': 'on',
|
||||
'bibliotheque': {'id': bibliotheque_id},
|
||||
'abonnements': abonnements,
|
||||
}
|
||||
return self.get_object().post_api('adherents', adherent)
|
||||
|
||||
|
||||
class BdpDetailView(DetailView):
|
||||
model = Bdp
|
||||
template_name = 'bdp/bdp_detail.html'
|
|
@ -0,0 +1,30 @@
|
|||
# passerelle - uniform access to multiple data sources and services
|
||||
# Copyright (C) 2016 Entr'ouvert
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import django.apps
|
||||
|
||||
class AppConfig(django.apps.AppConfig):
|
||||
name = 'choosit'
|
||||
label = 'choosit'
|
||||
|
||||
def get_after_urls(self):
|
||||
return None
|
||||
|
||||
def get_connector_model(self):
|
||||
from . import models
|
||||
return models.ChoositSMSGateway
|
||||
|
||||
default_app_config = 'choosit.AppConfig'
|
|
@ -0,0 +1,19 @@
|
|||
from django.contrib import admin
|
||||
|
||||
from .models import ChoositSMSGateway, ChoositRegisterGateway, ChoositRegisterNewsletter
|
||||
|
||||
class ChoositSMSGatewayAdmin(admin.ModelAdmin):
|
||||
prepopulated_fields = {'slug': ('title',)}
|
||||
list_display = ['title', 'slug', 'description', 'key',
|
||||
'default_country_code']
|
||||
|
||||
admin.site.register(ChoositSMSGateway, ChoositSMSGatewayAdmin)
|
||||
|
||||
|
||||
|
||||
class ChoositRegisterGatewayAdmin(admin.ModelAdmin):
|
||||
prepopulated_fields = {'slug': ('title',)}
|
||||
|
||||
admin.site.register(ChoositRegisterGateway, ChoositRegisterGatewayAdmin)
|
||||
admin.site.register(ChoositRegisterNewsletter)
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import requests
|
||||
import json
|
||||
import hashlib
|
||||
|
||||
class ChoositRegisterWS(object):
|
||||
def __init__(self, url, key):
|
||||
self.url = url
|
||||
self.key = key
|
||||
|
||||
def categories(self):
|
||||
return requests.post(self.url, data={'action': 'read'}).json()
|
||||
|
||||
def create(self, newsletter, email):
|
||||
return requests.post(self.url, data={'action': 'create', 'email': email,
|
||||
'newsletter': newsletter, 'hash': hashlib.sha1(self.key+email).hexdigest()
|
||||
}).json()
|
||||
|
||||
def delete(self, newsletter, email):
|
||||
return requests.post(self.url, data={'action': 'delete', 'email': email,
|
||||
'newsletter': newsletter, 'hash': hashlib.sha1(self.key+email).hexdigest()
|
||||
}).json()
|
||||
|
||||
def update(self, subscriptions, email):
|
||||
'''Returns { 'email': 'bdauvergne@entrouvert.com',
|
||||
'hash': 'ab60e5e1b226561092c082ca73a2ad9ee4527c7b',
|
||||
'status': 'ok'}
|
||||
or
|
||||
|
||||
{ 'email': 'bdauvergne@entrouvert.com',
|
||||
'hash': 'ab60e5dgd34543543',
|
||||
'status': 'nok',
|
||||
'error': 'error message'}
|
||||
'''
|
||||
if isinstance(subscriptions, basestring):
|
||||
subscriptions = subscriptions.split(',')
|
||||
params = {
|
||||
'action': 'update',
|
||||
'email': email,
|
||||
'hash': hashlib.sha1(self.key+email).hexdigest()
|
||||
}
|
||||
for i, subscription in enumerate(subscriptions):
|
||||
params['subscriptions[%d]'% i] = subscription
|
||||
res = requests.post(self.url, data=params)
|
||||
print res.request.body
|
||||
return res.json()
|
||||
|
||||
def subscriptions(self, email):
|
||||
'''Returns { 'email': 'johndoe@example.com',
|
||||
'hash': 'ef787...',
|
||||
'newsletters': { '1': 'newsletter 1', ... },
|
||||
'subscriptions': [ '1' ] }
|
||||
'''
|
||||
return requests.post(self.url, data={'action': 'read', 'email': email,
|
||||
'hash': hashlib.sha1(self.key+email).hexdigest()}).json()
|
||||
|
||||
def newsletters(self, categories):
|
||||
params = {'action': 'read_newsletters'}
|
||||
for i, categorie in enumerate(categories):
|
||||
params['categories[%d]' % i] = categorie
|
||||
return requests.post(self.url, data=params).json()
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
# ne fonctionne que depuis lantana
|
||||
# examples:
|
||||
# python choosit.py 'https://emailingeco.montpellier-agglo.com/ws/index.php' mykey subscriptions 'bdauvergne@entrouvert.com'
|
||||
# python choosit.py 'https://emailingeco.montpellier-agglo.com/ws/index.php' mykey update '315,316' 'bdauvergne@entrouvert.com'
|
||||
|
||||
ws = ChoositRegisterWS(sys.argv[1], sys.argv[2])
|
||||
func = getattr(ws, sys.argv[3])
|
||||
import pprint
|
||||
pprint.pprint(func(*sys.argv[4:]))
|
|
@ -0,0 +1,14 @@
|
|||
from django.utils.text import slugify
|
||||
from django import forms
|
||||
|
||||
from .models import ChoositRegisterGateway
|
||||
|
||||
class ChoositRegisterGatewayForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = ChoositRegisterGateway
|
||||
exclude = ('slug', 'users')
|
||||
|
||||
def save(self, commit=True):
|
||||
if not self.instance.slug:
|
||||
self.instance.slug = slugify(self.instance.title)
|
||||
return super(ChoositRegisterGatewayForm, self).save(commit=commit)
|
|
@ -0,0 +1,73 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
import passerelle.sms
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ChoositRegisterGateway',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('slug', models.SlugField()),
|
||||
('description', models.TextField()),
|
||||
('url', models.CharField(max_length=200)),
|
||||
('key', models.CharField(max_length=64)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'registration_choosit',
|
||||
'verbose_name': 'Choosit Registration',
|
||||
},
|
||||
bases=(models.Model,),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ChoositRegisterNewsletter',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('name', models.CharField(max_length=16)),
|
||||
('description', models.CharField(max_length=128, blank=True)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'newsletter_choosit',
|
||||
'verbose_name': 'Choosit Registration',
|
||||
},
|
||||
bases=(models.Model,),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ChoositSMSGateway',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('slug', models.SlugField()),
|
||||
('description', models.TextField()),
|
||||
('key', models.CharField(max_length=64)),
|
||||
('default_country_code', models.CharField(default='33', max_length=3)),
|
||||
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'sms_choosit',
|
||||
'verbose_name': 'Choosit',
|
||||
},
|
||||
bases=(models.Model, passerelle.sms.SMSGatewayMixin),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='choositregistergateway',
|
||||
name='newsletters',
|
||||
field=models.ManyToManyField(to='choosit.ChoositRegisterNewsletter', blank=True),
|
||||
preserve_default=True,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='choositregistergateway',
|
||||
name='users',
|
||||
field=models.ManyToManyField(to='base.ApiUser', blank=True),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,26 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('choosit', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='choositregistergateway',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Debug Enabled', blank=True, choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='choositsmsgateway',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Debug Enabled', blank=True, choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,26 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('choosit', '0002_auto_20160316_0528'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='choositregistergateway',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='choositsmsgateway',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,26 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('choosit', '0003_auto_20160316_0910'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='choositregistergateway',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='choositsmsgateway',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,198 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import requests
|
||||
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.db import models
|
||||
from django.core.urlresolvers import reverse
|
||||
|
||||
from passerelle.utils.jsonresponse import APIError
|
||||
from passerelle.base.models import BaseResource
|
||||
from passerelle.sms import SMSGatewayMixin
|
||||
|
||||
from .choosit import ChoositRegisterWS
|
||||
|
||||
|
||||
class ChoositSMSGateway(BaseResource, SMSGatewayMixin):
|
||||
key = models.CharField(max_length=64)
|
||||
default_country_code = models.CharField(max_length=3, default=u'33')
|
||||
# FIXME: add regexp field, to check destination and from format
|
||||
|
||||
TEST_DEFAULTS = {
|
||||
'create_kwargs': {
|
||||
'key': '1234',
|
||||
},
|
||||
'test_vectors': [
|
||||
{
|
||||
'response': '',
|
||||
'result': {
|
||||
'err': 1,
|
||||
'err_desc': 'Choosit error: some destinations failed',
|
||||
'data': [
|
||||
[u'33688888888', u'Choosit error: bad JSON response No JSON object '
|
||||
'could be decoded'],
|
||||
[u'33677777777', u'Choosit error: bad JSON response No JSON object '
|
||||
'could be decoded'],
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
'response': {
|
||||
'error': 'not ok',
|
||||
},
|
||||
'result': {
|
||||
'err': 1,
|
||||
'err_desc': 'Choosit error: some destinations failed',
|
||||
'data': [
|
||||
[u'33688888888', u'Choosit error: not ok'],
|
||||
[u'33677777777', u'Choosit error: not ok'],
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
'response': {
|
||||
'result': u'Envoi terminé',
|
||||
'sms_id': 1234,
|
||||
},
|
||||
'result': {
|
||||
'err': 0,
|
||||
'data': [
|
||||
[u'33688888888', {'result': u'Envoi terminé', 'sms_id': 1234}],
|
||||
[u'33677777777', {'result': u'Envoi terminé', 'sms_id': 1234}],
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
],
|
||||
}
|
||||
URL = 'http://sms.choosit.com/webservice'
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Choosit'
|
||||
db_table = 'sms_choosit'
|
||||
|
||||
@classmethod
|
||||
def get_verbose_name(cls):
|
||||
return cls._meta.verbose_name
|
||||
|
||||
@classmethod
|
||||
def get_icon_class(cls):
|
||||
return 'phone'
|
||||
|
||||
def send_msg(self, text, sender, destinations):
|
||||
"""Send a SMS using the Choosit provider"""
|
||||
# from http://sms.choosit.com/documentation_technique.html
|
||||
# unfortunately it lacks a batch API...
|
||||
destinations = self.clean_numbers(destinations, self.default_country_code, prefix='')
|
||||
results = []
|
||||
for dest in destinations:
|
||||
params = {
|
||||
'key': self.key,
|
||||
'recipient': dest,
|
||||
'content': text[:160],
|
||||
}
|
||||
data = {'data': json.dumps(params)}
|
||||
try:
|
||||
r = requests.post(self.URL, data=data)
|
||||
except requests.RequestException as e:
|
||||
results.append('Choosit error: %s' % e)
|
||||
else:
|
||||
try:
|
||||
output = r.json()
|
||||
except ValueError as e:
|
||||
results.append('Choosit error: bad JSON response %s' % e)
|
||||
else:
|
||||
if not isinstance(output, dict):
|
||||
results.append('Choosit error: JSON response is not a dict %r' % output)
|
||||
elif 'error' in output:
|
||||
results.append(u'Choosit error: %s' % output['error'])
|
||||
else:
|
||||
results.append(output)
|
||||
if any(isinstance(result, basestring) for result in results):
|
||||
raise APIError('Choosit error: some destinations failed',
|
||||
data=zip(destinations, results))
|
||||
return zip(destinations, results)
|
||||
|
||||
|
||||
class ChoositRegisterNewsletter(models.Model):
|
||||
name = models.CharField(max_length=16)
|
||||
description = models.CharField(max_length=128, blank=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Choosit Registration'
|
||||
db_table = 'newsletter_choosit'
|
||||
|
||||
def __unicode__(self):
|
||||
return u'%s: %s' % (self.name, self.description or u'<unnamed>')
|
||||
|
||||
|
||||
class ChoositRegisterGateway(BaseResource):
|
||||
category = _('Newsletter registration')
|
||||
|
||||
url = models.CharField(max_length=200)
|
||||
key = models.CharField(max_length=64)
|
||||
newsletters = models.ManyToManyField(ChoositRegisterNewsletter, blank=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Choosit Registration'
|
||||
db_table = 'registration_choosit'
|
||||
|
||||
@classmethod
|
||||
def get_verbose_name(cls):
|
||||
return cls._meta.verbose_name
|
||||
|
||||
@classmethod
|
||||
def get_icon_class(cls):
|
||||
return 'ressources'
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse('choosit-register-view', kwargs={'slug': self.slug})
|
||||
|
||||
@classmethod
|
||||
def get_add_url(cls):
|
||||
return reverse('choosit-register-add')
|
||||
|
||||
def get_edit_url(self):
|
||||
return reverse('choosit-register-edit', kwargs={'slug': self.slug})
|
||||
|
||||
def get_delete_url(self):
|
||||
return reverse('choosit-register-delete', kwargs={'slug': self.slug})
|
||||
|
||||
def get_list(self, user):
|
||||
reg = ChoositRegisterWS(self.url, self.key)
|
||||
|
||||
ws = reg.subscriptions(email=user or '')
|
||||
if 'error' in ws:
|
||||
raise APIError(ws['error'])
|
||||
newsletters = ws['newsletter']
|
||||
subscriptions = ws['subscriptions']
|
||||
|
||||
filters = dict([(n.name, n.description) for n in self.newsletters.all()])
|
||||
if filters:
|
||||
for name in newsletters.copy():
|
||||
if name not in filters:
|
||||
del newsletters[name]
|
||||
elif filters[name]:
|
||||
newsletters[name] = filters[name]
|
||||
|
||||
ret = []
|
||||
for id, name in newsletters.items():
|
||||
newsletter = {
|
||||
'name': id,
|
||||
'description': name,
|
||||
'transports': {'available': ['mail']}
|
||||
}
|
||||
if user:
|
||||
if id in subscriptions:
|
||||
newsletter['transports']['defined'] = ['mail']
|
||||
else:
|
||||
newsletter['transports']['defined'] = []
|
||||
ret.append(newsletter)
|
||||
|
||||
return ret
|
||||
|
||||
def post(self, user, data):
|
||||
subscriptions = [row['name'] for row in data if row['transports']]
|
||||
reg = ChoositRegisterWS(self.url, self.key)
|
||||
ws = reg.update(subscriptions, user)
|
||||
return {"message": ws['status']}
|
|
@ -0,0 +1,22 @@
|
|||
{% extends "passerelle/manage/service_view.html" %}
|
||||
{% load i18n passerelle %}
|
||||
|
||||
{% block description %}
|
||||
<p>
|
||||
Service URL : {{ object.url }}
|
||||
</p>
|
||||
{% endblock %}
|
||||
|
||||
{% block endpoints %}
|
||||
<ul>
|
||||
<li>{% trans 'Register:' %} <a href="{% url 'choosit-register' slug=object.slug %}"
|
||||
>{{ site_base_uri }}{% url 'choosit-register' slug=object.slug %}</a> (POST)</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
||||
{% block security %}
|
||||
<p>
|
||||
{% trans 'Accessing the listings is open, but posting requests is limited to the following API users:' %}
|
||||
</p>
|
||||
{% access_rights_table resource=object permission='can_post_request' %}
|
||||
{% endblock %}
|
|
@ -0,0 +1,14 @@
|
|||
from django.conf.urls import patterns, url
|
||||
from views import *
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^(?P<slug>[\w,-]+)/$', ChoositDetailView.as_view(), name='choosit-view'),
|
||||
url(r'^register/(?P<slug>[\w,-]+)/$', ChoositRegisterDetailView.as_view(), name='choosit-register-view'),
|
||||
url(r'^register/(?P<slug>[\w,-]+)/register$', ChoositRegisterView.as_view(), name='choosit-register'),
|
||||
)
|
||||
|
||||
management_urlpatterns = patterns('',
|
||||
url(r'^register/add$', ChoositRegisterCreateView.as_view(), name='choosit-register-add'),
|
||||
url(r'^register/(?P<slug>[\w,-]+)/edit$', ChoositRegisterUpdateView.as_view(), name='choosit-register-edit'),
|
||||
url(r'^register/(?P<slug>[\w,-]+)/delete$', ChoositRegisterDeleteView.as_view(), name='choosit-register-delete'),
|
||||
)
|
|
@ -0,0 +1,67 @@
|
|||
import json
|
||||
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.views.generic.edit import CreateView, UpdateView, DeleteView, View
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from passerelle.base.views import ResourceView
|
||||
from passerelle import utils
|
||||
|
||||
from .models import ChoositSMSGateway, ChoositRegisterGateway
|
||||
from .forms import ChoositRegisterGatewayForm
|
||||
|
||||
|
||||
class ChoositDetailView(ResourceView):
|
||||
model = ChoositSMSGateway
|
||||
template_name = 'passerelle/manage/messages_service_view.html'
|
||||
|
||||
|
||||
class ChoositRegisterDetailView(ResourceView):
|
||||
model = ChoositRegisterGateway
|
||||
template_name = 'choosit/choosit_register_detail.html'
|
||||
|
||||
|
||||
class ChoositRegisterCreateView(CreateView):
|
||||
model = ChoositRegisterGateway
|
||||
template_name = 'passerelle/manage/service_form.html'
|
||||
form_class = ChoositRegisterGatewayForm
|
||||
|
||||
|
||||
class ChoositRegisterUpdateView(UpdateView):
|
||||
model = ChoositRegisterGateway
|
||||
template_name = 'passerelle/manage/service_form.html'
|
||||
form_class = ChoositRegisterGatewayForm
|
||||
|
||||
|
||||
class ChoositRegisterDeleteView(DeleteView):
|
||||
model = ChoositRegisterGateway
|
||||
template_name = 'passerelle/manage/service_confirm_delete.html'
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse('manage-home')
|
||||
|
||||
|
||||
class ChoositRegisterView(View, SingleObjectMixin):
|
||||
model = ChoositRegisterGateway
|
||||
|
||||
@method_decorator(csrf_exempt)
|
||||
@utils.protected_api('can_post_request')
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
return super(ChoositRegisterView, self).dispatch(request, *args, **kwargs)
|
||||
|
||||
@utils.to_json('api')
|
||||
@method_decorator(csrf_exempt)
|
||||
def get(self, request, *args, **kwargs):
|
||||
user = request.GET.get('user')
|
||||
assert user, 'missing user parameter'
|
||||
return self.get_object().get_list(user)
|
||||
|
||||
@utils.to_json('api')
|
||||
def post(self, request, *args, **kwargs):
|
||||
user = request.GET.get('user')
|
||||
assert user, 'missing user parameter'
|
||||
data = json.loads(request.body)
|
||||
assert isinstance(data, list), 'body must be a JSON list'
|
||||
return self.get_object().post(user, data)
|
|
@ -0,0 +1,30 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('datasources', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ClicRdv',
|
||||
fields=[
|
||||
('basedatasource_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='datasources.BaseDataSource')),
|
||||
('server', models.CharField(default=b'sandbox.clicrdv.com', max_length=64, choices=[(b'www.clicrdv.com', b'Production (www.clicrdv.com)'), (b'sandbox.clicrdv.com', b'SandBox (sandbox.clicrdv.com)')])),
|
||||
('apikey', models.CharField(max_length=64)),
|
||||
('username', models.CharField(max_length=64)),
|
||||
('password', models.CharField(max_length=64)),
|
||||
('websource', models.CharField(max_length=64, null=True, blank=True)),
|
||||
('default_comment', models.CharField(max_length=250, null=True, blank=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Clicrdv Agenda',
|
||||
},
|
||||
bases=('datasources.basedatasource',),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('clicrdv', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='clicrdv',
|
||||
name='group_id',
|
||||
field=models.IntegerField(default=5242), # aka vincennes migration
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('clicrdv', '0002_clicrdv_group_id'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='clicrdv',
|
||||
name='group_id',
|
||||
field=models.IntegerField(default=0),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,56 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
from django.contrib.contenttypes.management import update_contenttypes
|
||||
|
||||
def migrate_clicrdv(apps, schema_editor):
|
||||
app_config = apps.app_configs['clicrdv']
|
||||
app_config.models_module = app_config.models_module or True
|
||||
update_contenttypes(app_config)
|
||||
ClicRdv = apps.get_model('clicrdv', 'ClicRdv')
|
||||
NewClicRdv = apps.get_model('clicrdv', 'NewClicRdv')
|
||||
AccessRight = apps.get_model('base', 'AccessRight')
|
||||
ContentType = apps.get_model('contenttypes', 'ContentType')
|
||||
old_ctype_id = apps.get_model('contenttypes', 'ContentType').objects.get(app_label='clicrdv', model='clicrdv').id
|
||||
new_ctype_id = apps.get_model('contenttypes', 'ContentType').objects.get(app_label='clicrdv', model='newclicrdv').id
|
||||
for old in ClicRdv.objects.all():
|
||||
new_dict = dict([x for x in old.__dict__.items() if x[0] not in ( 'id', 'basedatasource_ptr_id', '_state')])
|
||||
new_object = NewClicRdv(**new_dict)
|
||||
new_object.save()
|
||||
for access_right in AccessRight.objects.filter(resource_type_id=old_ctype_id, resource_pk=old.basedatasource_ptr_id):
|
||||
access_right.resource_pk = new_object.id
|
||||
access_right.save()
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base', '0002_auto_20151009_0326'),
|
||||
('contenttypes', '0001_initial'),
|
||||
('clicrdv', '0003_auto_20160920_0903'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='NewClicRdv',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('slug', models.SlugField()),
|
||||
('description', models.TextField()),
|
||||
('log_level', models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')])),
|
||||
('server', models.CharField(default=b'sandbox.clicrdv.com', max_length=64, choices=[(b'www.clicrdv.com', b'Production (www.clicrdv.com)'), (b'sandbox.clicrdv.com', b'SandBox (sandbox.clicrdv.com)')])),
|
||||
('group_id', models.IntegerField(default=0)),
|
||||
('apikey', models.CharField(max_length=64)),
|
||||
('username', models.CharField(max_length=64)),
|
||||
('password', models.CharField(max_length=64)),
|
||||
('websource', models.CharField(max_length=64, null=True, blank=True)),
|
||||
('default_comment', models.CharField(max_length=250, null=True, blank=True)),
|
||||
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Clicrdv Agenda',
|
||||
},
|
||||
),
|
||||
migrations.RunPython(migrate_clicrdv),
|
||||
]
|
|
@ -0,0 +1,16 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('clicrdv', '0004_newclicrdv'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.DeleteModel(name='ClicRdv'),
|
||||
migrations.RenameModel('NewClicRdv', 'ClicRdv'),
|
||||
]
|
|
@ -0,0 +1,216 @@
|
|||
'''
|
||||
Datasource for a ClicRDV instance.
|
||||
|
||||
It is a gateway to http://developers.clicrdv.com/fr/rest-api.html
|
||||
'''
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import urllib2
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.urlresolvers import reverse
|
||||
from django.db import models
|
||||
from django.utils.dateformat import format as date_format
|
||||
from django.utils.dateformat import time_format
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from passerelle.base.models import BaseResource
|
||||
from passerelle.utils.api import endpoint
|
||||
|
||||
CLICRDV_SERVERS = (
|
||||
('www.clicrdv.com', 'Production (www.clicrdv.com)'),
|
||||
('sandbox.clicrdv.com', 'SandBox (sandbox.clicrdv.com)')
|
||||
)
|
||||
|
||||
class ClicRdv(BaseResource):
|
||||
server = models.CharField(max_length=64,
|
||||
choices=CLICRDV_SERVERS,
|
||||
default='sandbox.clicrdv.com')
|
||||
group_id = models.IntegerField(default=0)
|
||||
apikey = models.CharField(max_length=64)
|
||||
username = models.CharField(max_length=64)
|
||||
password = models.CharField(max_length=64)
|
||||
websource = models.CharField(max_length=64, blank=True, null=True)
|
||||
default_comment = models.CharField(max_length=250, blank=True, null=True)
|
||||
|
||||
parameters = ('method', 'set', 'intervention', 'date', 'websource', 'id')
|
||||
|
||||
category = _('Business Process Connectors')
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('Clicrdv Agenda')
|
||||
|
||||
@classmethod
|
||||
def get_verbose_name(cls):
|
||||
return cls._meta.verbose_name
|
||||
|
||||
@classmethod
|
||||
def get_icon_class(cls):
|
||||
return 'clock'
|
||||
|
||||
def get_request(self, uri):
|
||||
url = 'https://%s/api/v1/groups/%s/%s' % (self.server, self.group_id, uri)
|
||||
if '?' in url:
|
||||
url = url + '&apikey=%s&format=json' % self.apikey
|
||||
else:
|
||||
url = url + '?apikey=%s&format=json' % self.apikey
|
||||
req = urllib2.Request(url)
|
||||
authheader = 'Basic ' + \
|
||||
base64.encodestring('%s:%s' % (self.username, self.password))[:-1]
|
||||
req.add_header('Authorization', authheader)
|
||||
return req
|
||||
|
||||
def get_json(self, uri):
|
||||
req = self.get_request(uri)
|
||||
return json.load(urllib2.urlopen(req))
|
||||
|
||||
@endpoint(name='interventionsets', serializer_type='json-api')
|
||||
def get_interventionsets(self, request, **kwargs):
|
||||
records = self.get_json('interventionsets').get('records')
|
||||
records.sort(lambda x,y: cmp(x['sort'], y['sort']))
|
||||
ret = []
|
||||
for record in records:
|
||||
if record.get('publicname'):
|
||||
ret.append({'id': record['id'], 'text': record['publicname'], 'details': record})
|
||||
return ret
|
||||
|
||||
@endpoint(name='interventionsets', pattern='(?P<set>\d+)/', serializer_type='json-api')
|
||||
def get_interventions(self, request, set, **kwargs):
|
||||
ret = []
|
||||
records = self.get_json('interventions?interventionset_id=%s' % set).get('records')
|
||||
records.sort(lambda x,y: cmp(x['sort'], y['sort']))
|
||||
for record in records:
|
||||
if record.get('publicname'):
|
||||
ret.append({'id': record['id'], 'text': record['publicname'], 'details': record})
|
||||
return ret
|
||||
|
||||
def get_available_timeslots(self, intervention, date_start=None, date_end=None):
|
||||
timeslots = []
|
||||
iid = int(intervention)
|
||||
request_uri = 'availabletimeslots?intervention_ids[]=%s' % iid
|
||||
if date_start is None:
|
||||
date_start = datetime.datetime.today().strftime('%Y-%m-%d')
|
||||
if date_end is None:
|
||||
date_end = (datetime.datetime.today() + datetime.timedelta(366)).strftime('%Y-%m-%d')
|
||||
if date_start:
|
||||
request_uri = request_uri + '&start=%s' % urllib2.quote(date_start)
|
||||
if date_end:
|
||||
request_uri = request_uri + '&end=%s' % urllib2.quote(date_end)
|
||||
for timeslot in self.get_json(request_uri).get('availabletimeslots'):
|
||||
timeslots.append(timeslot.get('start'))
|
||||
timeslots.sort()
|
||||
return timeslots
|
||||
|
||||
def get_datetimes(self, intervention, **kwargs):
|
||||
datetimes = []
|
||||
for timeslot in self.get_available_timeslots(intervention):
|
||||
parsed = datetime.datetime.strptime(timeslot, '%Y-%m-%d %H:%M:%S')
|
||||
datetimed = {'id': parsed.strftime('%Y-%m-%d-%H:%M:%S'),
|
||||
'text': date_format(parsed, 'j F Y H:i')}
|
||||
datetimes.append(datetimed)
|
||||
datetimes.sort(lambda x,y: cmp(x.get('id'), y.get('id')))
|
||||
return datetimes
|
||||
|
||||
def get_dates(self, intervention, **kwargs):
|
||||
dates = []
|
||||
for timeslot in self.get_available_timeslots(intervention):
|
||||
parsed = datetime.datetime.strptime(timeslot, '%Y-%m-%d %H:%M:%S')
|
||||
date = {'id': parsed.strftime('%Y-%m-%d'),
|
||||
'text': date_format(parsed, 'j F Y')}
|
||||
if date in dates:
|
||||
continue
|
||||
dates.append(date)
|
||||
dates.sort(lambda x,y: cmp(x.get('id'), y.get('id')))
|
||||
return dates
|
||||
|
||||
def get_times(self, intervention, date, **kwargs):
|
||||
if not date:
|
||||
raise Exception('no date value')
|
||||
times = []
|
||||
for timeslot in self.get_available_timeslots(intervention,
|
||||
date_start='%s 00:00:00' % date,
|
||||
date_end='%s 23:59:59' % date):
|
||||
parsed = datetime.datetime.strptime(timeslot, '%Y-%m-%d %H:%M:%S')
|
||||
timed = {'id': parsed.strftime('%H:%M:%S'),
|
||||
'text': time_format(parsed, 'H:i')}
|
||||
times.append(timed)
|
||||
times.sort(lambda x,y: cmp(x.get('id'), y.get('id')))
|
||||
return times
|
||||
|
||||
def cancel(self, id, **kwargs):
|
||||
appointment_id = int(id)
|
||||
req = self.get_request('appointments/%s' % appointment_id)
|
||||
req.get_method = (lambda: 'DELETE')
|
||||
try:
|
||||
fd = urllib2.urlopen(req)
|
||||
none = fd.read()
|
||||
except urllib2.HTTPError as e:
|
||||
# clicrdv will return a "Bad Request" (HTTP 400) response
|
||||
# when it's not possible to remove an appointment
|
||||
# (for example because it's too late)
|
||||
response = e.read()
|
||||
response = json.loads(response)
|
||||
return {'success': False, 'error': response}
|
||||
return {'success': True}
|
||||
|
||||
|
||||
def create_appointment(self, intervention, websource, data):
|
||||
fields = data.get('fields') or {}
|
||||
extra = data.get('extra') or {}
|
||||
def get_data(key, default=None):
|
||||
return data.get(key) or extra.get(key) or fields.get(key) or default
|
||||
if intervention:
|
||||
intervention = int(intervention)
|
||||
else:
|
||||
intervention = int(get_data('clicrdv_intervention_raw'))
|
||||
date = get_data('clicrdv_date_raw')
|
||||
time = get_data('clicrdv_time_raw')
|
||||
if not date and not time:
|
||||
date = get_data('clicrdv_datetime_raw')
|
||||
else:
|
||||
date = date + ' ' + time
|
||||
if websource is None:
|
||||
websource = self.websource or ''
|
||||
appointment = {
|
||||
'fiche': {
|
||||
'firstname': get_data('clicrdv_firstname') or '-',
|
||||
'lastname': get_data('clicrdv_lastname') or '-',
|
||||
'email': get_data('clicrdv_email', ''),
|
||||
'firstphone': get_data('clicrdv_firstphone', ''),
|
||||
'secondphone': get_data('clicrdv_secondphone', ''),
|
||||
},
|
||||
'date': date,
|
||||
'intervention_ids': [intervention],
|
||||
'websource': websource,
|
||||
}
|
||||
comments = get_data('clicrdv_comments') or self.default_comment
|
||||
if comments:
|
||||
appointment['comments'] = comments
|
||||
# optional parameters, if any...
|
||||
for fieldname in (fields.keys() + extra.keys() + data.keys()):
|
||||
if fieldname.startswith('clicrdv_fiche_'):
|
||||
appointment['fiche'][fieldname[14:]] = get_data(fieldname) or ''
|
||||
req = self.get_request('appointments')
|
||||
req.add_data(json.dumps({'appointment': appointment}))
|
||||
req.add_header('Content-Type', 'application/json')
|
||||
try:
|
||||
fd = urllib2.urlopen(req)
|
||||
except urllib2.HTTPError, e:
|
||||
try:
|
||||
error = json.load(e.fp)[0].get('error')
|
||||
except:
|
||||
error = 'Unknown error (Passerelle)'
|
||||
return {
|
||||
'success': False,
|
||||
'error': error,
|
||||
}
|
||||
else:
|
||||
success = True
|
||||
response = json.load(fd)
|
||||
appointment_id = response.get('records')[0].get('id')
|
||||
return {
|
||||
'success': True,
|
||||
'appointment_id': appointment_id,
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
{% extends "passerelle/manage/service_view.html" %}
|
||||
{% load i18n passerelle %}
|
||||
|
||||
{% block description %}
|
||||
<p>
|
||||
Server: {{ object.server }}
|
||||
</p>
|
||||
{% endblock %}
|
||||
|
||||
{% block endpoints %}
|
||||
<ul>
|
||||
<li>{% trans 'Listing all sets:' %} <a href="{% url 'generic-endpoint' connector="clicrdv" slug=object.slug endpoint="interventionsets" slug=object.slug %}"
|
||||
>{{ site_base_uri }}{% url 'generic-endpoint' connector="clicrdv" slug=object.slug endpoint="interventionsets" slug=object.slug %}</a></li>
|
||||
<li>{% trans 'Listing interventions in a set:' %} <a
|
||||
>{{ site_base_uri }}{% url 'generic-endpoint' connector="clicrdv" slug=object.slug endpoint="interventionsets" slug=object.slug %}/<i><set_id></i></a></li>
|
||||
<li>{% trans 'Listing of free dates and times for an intervention:' %} <a
|
||||
>{{ site_base_uri }}{% url 'clicrdv-view' slug=object.slug %}interventions/<i><intervention_id></i>/datetimes</a></li>
|
||||
<li>{% trans 'Listing of free dates for an intervention:' %} <a
|
||||
>{{ site_base_uri }}{% url 'clicrdv-view' slug=object.slug %}interventions/<i><intervention_id></i>/dates</a></li>
|
||||
<li>{% trans 'Listing of free times a given date for an intervention:' %} <a
|
||||
>{{ site_base_uri }}{% url 'clicrdv-view' slug=object.slug %}interventions/<i><intervention_id></i>/<i><date></i>/times</a></li>
|
||||
<li>{% trans 'Creating a new appointment:' %} <a
|
||||
>{{ site_base_uri }}{% url 'clicrdv-create-appointment-qs' slug=object.slug %}</a> (POST)</li>
|
||||
<li>{% trans 'Cancelling an appointment:' %} <a
|
||||
>{{ site_base_uri }}{% url 'clicrdv-view' slug=object.slug %}<i><appointment_id></i>/cancel</a></li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
||||
{% block security %}
|
||||
<p>
|
||||
{% trans 'Accessing the listings is open, but creation and cancellation of appointments requests is limited to the following API users:' %}
|
||||
</p>
|
||||
|
||||
{% access_rights_table resource=object permission='can_manage_appointment' %}
|
||||
{% endblock %}
|
|
@ -0,0 +1,23 @@
|
|||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.conf.urls import patterns, include, url
|
||||
|
||||
from passerelle.urls_utils import decorated_includes, required, app_enabled
|
||||
|
||||
from views import *
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^(?P<slug>[\w,-]+)/$', ClicRdvDetailView.as_view(), name='clicrdv-view'),
|
||||
|
||||
url(r'^(?P<slug>[\w,-]+)/interventions/(?P<intervention_id>\d+)/datetimes/$',
|
||||
DateTimesView.as_view(), name='clicrdv-datetimes'),
|
||||
url(r'^(?P<slug>[\w,-]+)/interventions/(?P<intervention_id>\d+)/dates/$',
|
||||
DatesView.as_view(), name='clicrdv-dates'),
|
||||
url(r'^(?P<slug>[\w,-]+)/interventions/(?P<intervention_id>\d+)/(?P<date>[\d-]+)/times$',
|
||||
TimesView.as_view(), name='clicrdv-times'),
|
||||
url(r'^(?P<slug>[\w,-]+)/interventions/(?P<intervention_id>\d+)/create$',
|
||||
csrf_exempt(CreateAppointmentView.as_view()), name='clicrdv-create-appointment'),
|
||||
url(r'^(?P<slug>[\w,-]+)/create$',
|
||||
csrf_exempt(CreateAppointmentView.as_view()), name='clicrdv-create-appointment-qs'),
|
||||
url(r'^(?P<slug>[\w,-]+)/(?P<appointment_id>\d+)/cancel$',
|
||||
CancelAppointmentView.as_view(), name='clicrdv-cancel-appointment'),
|
||||
)
|
|
@ -0,0 +1,107 @@
|
|||
import json
|
||||
|
||||
from django.views.generic.base import View
|
||||
from django.views.generic.detail import SingleObjectMixin, DetailView
|
||||
|
||||
from passerelle import utils
|
||||
|
||||
from .models import ClicRdv
|
||||
|
||||
|
||||
class ClicRdvDetailView(DetailView):
|
||||
model = ClicRdv
|
||||
|
||||
|
||||
class DateTimesView(View, SingleObjectMixin):
|
||||
"""list of free date× in a intervention
|
||||
|
||||
input: https//passerelle/clicrdv/foobar/interventions/887/datetimes
|
||||
"""
|
||||
model = ClicRdv
|
||||
|
||||
@utils.to_json('api')
|
||||
def get(self, request, intervention_id, *args, **kwargs):
|
||||
return self.get_object().get_datetimes(intervention_id)
|
||||
|
||||
|
||||
class DatesView(View, SingleObjectMixin):
|
||||
"""list of free dates in a intervention
|
||||
|
||||
input: https//passerelle/clicrdv/foobar/interventions/887/dates
|
||||
output:
|
||||
{ data: [ { id: '2014-05-07', text: "7 mai 2014" },
|
||||
{ id: '2014-05-13', text: "13 mai 2014" } ], err: 0 }
|
||||
"""
|
||||
model = ClicRdv
|
||||
|
||||
@utils.to_json('api')
|
||||
def get(self, request, intervention_id, *args, **kwargs):
|
||||
return self.get_object().get_dates(intervention_id)
|
||||
|
||||
|
||||
class TimesView(View, SingleObjectMixin):
|
||||
"""list of free time in a date, for an intervention
|
||||
|
||||
input: https//passerelle/clicrdv/foobar/interventions/887/2014-05-07/times
|
||||
output:
|
||||
{ data: [ { id: '15:10:00', text: "15:10" },
|
||||
{ id: '15:30:00', text: "15:30" } ], err: 0 }
|
||||
"""
|
||||
model = ClicRdv
|
||||
|
||||
@utils.to_json('api')
|
||||
def get(self, request, intervention_id, date, *args, **kwargs):
|
||||
return self.get_object().get_times(intervention_id, date)
|
||||
|
||||
|
||||
class CreateAppointmentView(View, SingleObjectMixin):
|
||||
"""create an appointment
|
||||
|
||||
input (POST: URL and payload)
|
||||
https//passerelle/data/clicrdv-title/interventions/887/create[?websource=Web]
|
||||
https//passerelle/data/clicrdv-title/create?[intervention=887][&websource=Web]
|
||||
{
|
||||
'clicrdv_intervention_raw': ..., # optional if present in URL
|
||||
'clicrdv_firstname': ...,
|
||||
'clicrdv_lastname': ...,
|
||||
'clicrdv_email': ...,
|
||||
'clicrdv_firstphone': ...,
|
||||
'clicrdv_secondphone': ...,
|
||||
'clicrdv_date_raw': ..., 'clicrdv_time_raw': ..., # or 'clicrdv_datetime_raw': ...,
|
||||
'clicrdv_comments': ..., # optional
|
||||
'clicrdc_fiche_xxx': ... # add a optional "xxx" value in fiche
|
||||
}
|
||||
|
||||
The various keys will also be looked in the 'fields' and 'extra'
|
||||
dictionaries, if existing. Order is root/extra/fields.
|
||||
|
||||
output:
|
||||
{ data: { 'success': true, 'appointment_id': 123 }, err: 0 }
|
||||
"""
|
||||
model = ClicRdv
|
||||
|
||||
@utils.protected_api('can_manage_appointment')
|
||||
@utils.to_json('api')
|
||||
def post(self, request, intervention_id=None, *args, **kwargs):
|
||||
if intervention_id is None:
|
||||
intervention_id = self.request.GET.get('intervention')
|
||||
data = json.loads(request.body)
|
||||
return self.get_object().create_appointment(
|
||||
intervention_id,
|
||||
self.request.GET.get('websource'),
|
||||
data)
|
||||
|
||||
|
||||
class CancelAppointmentView(View, SingleObjectMixin):
|
||||
"""cancel an appointment
|
||||
|
||||
input: https//passerelle/clicrdv/foobar/1234/cancel
|
||||
output:
|
||||
{ data: { 'success': true }, err: 0 }
|
||||
"""
|
||||
model = ClicRdv
|
||||
|
||||
@utils.protected_api('can_manage_appointment')
|
||||
@utils.to_json('api')
|
||||
def get(self, request, appointment_id, *args, **kwargs):
|
||||
return self.get_object().cancel(appointment_id)
|
|
@ -0,0 +1,28 @@
|
|||
# passerelle - uniform access to multiple data sources and services
|
||||
# Copyright (C) 2016 Entr'ouvert
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import django.apps
|
||||
|
||||
class AppConfig(django.apps.AppConfig):
|
||||
name = 'csvdatasource'
|
||||
label = 'csvdatasource'
|
||||
|
||||
def get_connector_model(self):
|
||||
from . import models
|
||||
return models.CsvDataSource
|
||||
|
||||
default_app_config = 'csvdatasource.AppConfig'
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
# passerelle - uniform access to multiple data sources and services
|
||||
# Copyright (C) 2016 Entr'ouvert
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from .models import Query, get_code, identifier_re
|
||||
|
||||
|
||||
class QueryForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Query
|
||||
widgets = {
|
||||
'resource': forms.HiddenInput(),
|
||||
'filters': forms.Textarea(attrs={'rows': 2}),
|
||||
'projections': forms.Textarea(attrs={'rows': 2}),
|
||||
'order': forms.Textarea(attrs={'rows': 2}),
|
||||
'distinct': forms.Textarea(attrs={'rows': 2}),
|
||||
}
|
||||
fields = '__all__'
|
||||
|
||||
def clean_lines_of_expressions(self, lines, named=False):
|
||||
if not lines:
|
||||
return lines
|
||||
errors = []
|
||||
for i, line in enumerate(lines.splitlines()):
|
||||
if named:
|
||||
line = line.split(':', 1)
|
||||
if len(line) != 2:
|
||||
errors.append(ValidationError(
|
||||
_('Syntax error line %d: each line must be prefixed '
|
||||
'with an identifier followed by a colon.') % (i + 1)))
|
||||
continue
|
||||
name, line = line
|
||||
if not identifier_re.match(name):
|
||||
errors.append(
|
||||
ValidationError(_('Syntax error line %d: invalid identifier, '
|
||||
'it must starts with a letter and only '
|
||||
'contains letters, digits and _.') % (i + 1)))
|
||||
continue
|
||||
try:
|
||||
get_code(line)
|
||||
except SyntaxError as e:
|
||||
errors.append(ValidationError(
|
||||
_('Syntax error line %(line)d at character %(character)d') % {
|
||||
'line': i + 1,
|
||||
'character': e.offset
|
||||
}))
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
return lines
|
||||
|
||||
def clean_filters(self):
|
||||
return self.clean_lines_of_expressions(self.data.get('filters'))
|
||||
|
||||
def clean_projections(self):
|
||||
return self.clean_lines_of_expressions(self.data.get('projections'), named=True)
|
||||
|
||||
def clean_order(self):
|
||||
return self.clean_lines_of_expressions(self.data.get('order'))
|
||||
|
||||
def clean_distinct(self):
|
||||
return self.clean_lines_of_expressions(self.data.get('distinct'))
|
|
@ -0,0 +1,70 @@
|
|||
DELIMITER = '__'
|
||||
|
||||
class InvalidOperatorError(Exception):
|
||||
pass
|
||||
|
||||
compare_str = cmp
|
||||
|
||||
|
||||
def is_int(value):
|
||||
try:
|
||||
int(value)
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
class Lookup(object):
|
||||
|
||||
def contains(self, index, value):
|
||||
return lambda x: value in x[index]
|
||||
|
||||
def icontains(self, index, value):
|
||||
return lambda x: value.lower() in x[index].lower()
|
||||
|
||||
def gt(self, index, value):
|
||||
return lambda x: int(x[index]) > int(value)
|
||||
|
||||
def igt(self, index, value):
|
||||
return lambda x: compare_str(x[index].lower(), value.lower()) > 0
|
||||
|
||||
def ge(self, index, value):
|
||||
return lambda x: int(x[index]) >= int(value)
|
||||
|
||||
def ige(self, index, value):
|
||||
return lambda x: compare_str(x[index].lower(), value.lower()) >= 0
|
||||
|
||||
def lt(self, index, value):
|
||||
return lambda x: int(x[index]) < int(value)
|
||||
|
||||
def ilt(self, index, value):
|
||||
return lambda x: compare_str(x[index].lower(), value.lower()) < 0
|
||||
|
||||
def le(self, index, value):
|
||||
return lambda x: int(x[index]) <= int(value)
|
||||
|
||||
def ile(self, index, value):
|
||||
return lambda x: compare_str(x[index].lower(), value.lower()) <= 0
|
||||
|
||||
def eq(self, index, value):
|
||||
if is_int(value):
|
||||
return lambda x: int(value) == int(x[index])
|
||||
return lambda x: value == x[index]
|
||||
|
||||
def ieq(self, index, value):
|
||||
return lambda x: value.lower() == x[index].lower()
|
||||
|
||||
def ne(self, index, value):
|
||||
if is_int(value):
|
||||
return lambda x: int(value) != int(x[index])
|
||||
return lambda x: value != x[index]
|
||||
|
||||
def ine(self, index, value):
|
||||
return lambda x: value.lower() != x[index].lower()
|
||||
|
||||
|
||||
def get_lookup(operator, index, value):
|
||||
try:
|
||||
return getattr(Lookup(), operator)(index, value)
|
||||
except (AttributeError,):
|
||||
raise InvalidOperatorError('%s is not a valid operator' % operator)
|
|
@ -0,0 +1,35 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('base', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='CsvDataSource',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('title', models.CharField(max_length=50)),
|
||||
('slug', models.SlugField()),
|
||||
('description', models.TextField()),
|
||||
('csv_file', models.FileField(upload_to=b'csv', verbose_name='CSV File')),
|
||||
('columns_keynames', models.CharField(default=b'id, text',
|
||||
help_text='ex: id,text,data1,data2',
|
||||
max_length=256,
|
||||
verbose_name='Column keynames',
|
||||
blank=True)),
|
||||
('skip_header', models.BooleanField(default=False, verbose_name='Skip first line')),
|
||||
('users', models.ManyToManyField(to='base.ApiUser', blank=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'CSV File',
|
||||
},
|
||||
bases=(models.Model,),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='csvdatasource',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Debug Enabled', blank=True, choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0002_csvdatasource_log_level'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='csvdatasource',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'DEBUG', b'DEBUG'), (b'INFO', b'INFO')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0003_auto_20160316_0910'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='csvdatasource',
|
||||
name='log_level',
|
||||
field=models.CharField(default=b'NOTSET', max_length=10, verbose_name='Log Level', choices=[(b'NOTSET', b'NOTSET'), (b'DEBUG', b'DEBUG'), (b'INFO', b'INFO'), (b'WARNING', b'WARNING'), (b'ERROR', b'ERROR'), (b'CRITICAL', b'CRITICAL'), (b'FATAL', b'FATAL')]),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,21 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
import jsonfield.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0004_auto_20160407_0456'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='csvdatasource',
|
||||
name='_dialect_options',
|
||||
field=jsonfield.fields.JSONField(default=dict, editable=False),
|
||||
preserve_default=True,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
import jsonfield.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0005_csvdatasource__dialect_options'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='csvdatasource',
|
||||
name='_dialect_options',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='csvdatasource',
|
||||
name='_dialect_options',
|
||||
field=jsonfield.fields.JSONField(null=True, editable=False),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,30 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0006_auto_20160905_1031'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Query',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('slug', models.SlugField(verbose_name='Name')),
|
||||
('filters', models.TextField(help_text='List of filter clauses (Python expression)', verbose_name='Filters', blank=True)),
|
||||
('projections', models.TextField(help_text='List of projections (name:expression)', verbose_name='Projections', blank=True)),
|
||||
('order', models.TextField(help_text='Ordering columns', verbose_name='Order', blank=True)),
|
||||
('distinct', models.TextField(help_text='Distinct columns', verbose_name='Distinct', blank=True)),
|
||||
('structure', models.CharField(default=b'dict', help_text='Data structure used for the response', max_length=20, verbose_name='Structure', choices=[(b'array', 'Array'), (b'dict', 'Dictionary'), (b'tuples', 'Tuples'), (b'onerow', 'Single Row'), (b'one', 'Single Value')])),
|
||||
('resource', models.ForeignKey(to='csvdatasource.CsvDataSource')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['slug'],
|
||||
},
|
||||
),
|
||||
]
|
|
@ -0,0 +1,30 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0007_query'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='query',
|
||||
name='description',
|
||||
field=models.TextField(verbose_name='Description', blank=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='query',
|
||||
name='label',
|
||||
field=models.CharField(default='', max_length=100, verbose_name='Label'),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='query',
|
||||
name='slug',
|
||||
field=models.SlugField(verbose_name='Name (slug)'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,23 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import models, migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('csvdatasource', '0008_auto_20161025_1156'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='csvdatasource',
|
||||
options={'verbose_name': 'Spreadsheet File'},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='csvdatasource',
|
||||
name='sheet_name',
|
||||
field=models.CharField(max_length=150, verbose_name='Sheet name', blank=True),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,362 @@
|
|||
# passerelle - uniform access to multiple data sources and services
|
||||
# Copyright (C) 2016 Entr'ouvert
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import re
|
||||
import csv
|
||||
import itertools
|
||||
from collections import OrderedDict
|
||||
from pyexcel_ods import get_data as get_data_ods
|
||||
from pyexcel_xls import get_data as get_data_xls
|
||||
|
||||
import jsonfield
|
||||
|
||||
from django.utils.encoding import smart_text
|
||||
from django.db import models
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from passerelle.base.models import BaseResource
|
||||
from passerelle.utils.jsonresponse import APIError
|
||||
from passerelle.utils.api import endpoint
|
||||
|
||||
import lookups
|
||||
|
||||
identifier_re = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE)
|
||||
|
||||
|
||||
code_cache = OrderedDict()
|
||||
|
||||
|
||||
def get_code(expr):
|
||||
# limit size of code cache to 1024
|
||||
if len(code_cache) > 1024:
|
||||
for key in code_cache.keys()[:len(code_cache) - 1024]:
|
||||
code_cache.pop(key)
|
||||
if expr not in code_cache:
|
||||
code_cache[expr] = compile(expr, '<inline>', 'eval')
|
||||
return code_cache[expr]
|
||||
|
||||
|
||||
class Query(models.Model):
|
||||
resource = models.ForeignKey('CsvDataSource')
|
||||
slug = models.SlugField(_('Name (slug)'))
|
||||
label = models.CharField(_('Label'), max_length=100)
|
||||
description = models.TextField(_('Description'), blank=True)
|
||||
filters = models.TextField(_('Filters'), blank=True,
|
||||
help_text=_('List of filter clauses (Python expression)'))
|
||||
projections = models.TextField(_('Projections'), blank=True,
|
||||
help_text=_('List of projections (name:expression)'))
|
||||
order = models.TextField(_('Order'), blank=True,
|
||||
help_text=_('Ordering columns'))
|
||||
distinct = models.TextField(_('Distinct'), blank=True,
|
||||
help_text=_('Distinct columns'))
|
||||
structure = models.CharField(_('Structure'),
|
||||
max_length=20,
|
||||
choices=[
|
||||
('array', _('Array')),
|
||||
('dict', _('Dictionary')),
|
||||
('tuples', _('Tuples')),
|
||||
('onerow', _('Single Row')),
|
||||
('one', _('Single Value'))],
|
||||
default='dict',
|
||||
help_text=_('Data structure used for the response'))
|
||||
|
||||
class Meta:
|
||||
ordering = ['slug']
|
||||
|
||||
def get_list(self, attribute):
|
||||
if not getattr(self, attribute):
|
||||
return []
|
||||
return getattr(self, attribute).strip().splitlines()
|
||||
|
||||
|
||||
class CsvDataSource(BaseResource):
|
||||
csv_file = models.FileField(_('CSV File'), upload_to='csv')
|
||||
columns_keynames = models.CharField(
|
||||
max_length=256,
|
||||
verbose_name=_('Column keynames'),
|
||||
default='id, text',
|
||||
help_text=_('ex: id,text,data1,data2'), blank=True)
|
||||
skip_header = models.BooleanField(_('Skip first line'), default=False)
|
||||
_dialect_options = jsonfield.JSONField(editable=False, null=True)
|
||||
sheet_name = models.CharField(_('Sheet name'), blank=True, max_length=150)
|
||||
|
||||
category = _('Data Sources')
|
||||
|
||||
class Meta:
|
||||
verbose_name = _('Spreadsheet File')
|
||||
|
||||
def clean(self, *args, **kwargs):
|
||||
file_type = self.csv_file.name.split('.')[-1]
|
||||
if file_type in ('ods', 'xls', 'xlsx') and not self.sheet_name:
|
||||
raise ValidationError(_('You must specify a sheet name'))
|
||||
return super(CsvDataSource, self).clean(*args, **kwargs)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
file_type = self.csv_file.name.split('.')[-1]
|
||||
if file_type not in ('ods', 'xls', 'xlsx'):
|
||||
content = self.get_content_without_bom()
|
||||
dialect = csv.Sniffer().sniff(content)
|
||||
self.dialect_options = {
|
||||
k: v for k, v in vars(dialect).items() if not k.startswith('_')
|
||||
}
|
||||
return super(CsvDataSource, self).save(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def dialect_options(self):
|
||||
"""turn dict items into string
|
||||
"""
|
||||
# Set dialect_options if None
|
||||
if self._dialect_options is None:
|
||||
self.save()
|
||||
|
||||
options = {}
|
||||
for k, v in self._dialect_options.items():
|
||||
if isinstance(v, unicode):
|
||||
v = v.encode('ascii')
|
||||
options[k.encode('ascii')] = v
|
||||
|
||||
return options
|
||||
|
||||
@dialect_options.setter
|
||||
def dialect_options(self, value):
|
||||
self._dialect_options = value
|
||||
|
||||
@classmethod
|
||||
def get_verbose_name(cls):
|
||||
return cls._meta.verbose_name
|
||||
|
||||
@classmethod
|
||||
def get_icon_class(cls):
|
||||
return 'grid'
|
||||
|
||||
@classmethod
|
||||
def is_enabled(cls):
|
||||
return True
|
||||
|
||||
def get_content_without_bom(self):
|
||||
self.csv_file.seek(0)
|
||||
content = self.csv_file.read()
|
||||
return content.decode('utf-8-sig', 'ignore').encode('utf-8')
|
||||
|
||||
def get_rows(self):
|
||||
file_type = self.csv_file.name.split('.')[-1]
|
||||
if file_type not in ('ods', 'xls', 'xlsx'):
|
||||
content = self.get_content_without_bom()
|
||||
reader = csv.reader(content.splitlines(), **self.dialect_options)
|
||||
rows = list(reader)
|
||||
|
||||
else:
|
||||
if file_type == 'ods':
|
||||
content = get_data_ods(self.csv_file)
|
||||
|
||||
elif file_type == 'xls' or file_type == 'xlsx':
|
||||
content = get_data_xls(self.csv_file.path)
|
||||
|
||||
if self.sheet_name not in content:
|
||||
return []
|
||||
|
||||
rows = content[self.sheet_name]
|
||||
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
if self.skip_header:
|
||||
rows = rows[1:]
|
||||
|
||||
return [[smart_text(x) for x in y] for y in rows]
|
||||
|
||||
def get_data(self, filters=None):
|
||||
titles = [t.strip() for t in self.columns_keynames.split(',')]
|
||||
indexes = [titles.index(t) for t in titles if t]
|
||||
caption = [titles[i] for i in indexes]
|
||||
|
||||
# validate filters (appropriate columns must exist)
|
||||
if filters:
|
||||
for filter_key in filters.keys():
|
||||
if not filter_key.split(lookups.DELIMITER)[0] in titles:
|
||||
del filters[filter_key]
|
||||
|
||||
rows = self.get_rows()
|
||||
|
||||
data = []
|
||||
|
||||
# build a generator of all filters
|
||||
def filters_generator(filters, titles):
|
||||
if not filters:
|
||||
return
|
||||
for key, value in filters.items():
|
||||
try:
|
||||
key, op = key.split(lookups.DELIMITER)
|
||||
except (ValueError,):
|
||||
op = 'eq'
|
||||
|
||||
index = titles.index(key)
|
||||
|
||||
yield lookups.get_lookup(op, index, value)
|
||||
|
||||
# apply filters to data
|
||||
def super_filter(filters, data):
|
||||
for f in filters:
|
||||
data = itertools.ifilter(f, data)
|
||||
return data
|
||||
|
||||
matches = super_filter(
|
||||
filters_generator(filters, titles), rows
|
||||
)
|
||||
|
||||
for row in matches:
|
||||
line = []
|
||||
for i in indexes:
|
||||
try:
|
||||
line.append(row[i])
|
||||
except IndexError:
|
||||
line.append('')
|
||||
|
||||
data.append(dict(zip(caption, line)))
|
||||
|
||||
return data
|
||||
|
||||
@property
|
||||
def titles(self):
|
||||
return [smart_text(t.strip()) for t in self.columns_keynames.split(',')]
|
||||
|
||||
@endpoint('json-api', perm='can_access', methods=['get'],
|
||||
name='query', pattern='^(?P<query_name>[\w-]+)/$')
|
||||
def select(self, request, query_name, **kwargs):
|
||||
try:
|
||||
query = Query.objects.get(resource=self.id, slug=query_name)
|
||||
except Query.DoesNotExist:
|
||||
raise APIError(u'no such query')
|
||||
|
||||
titles = self.titles
|
||||
rows = self.get_rows()
|
||||
data = [dict(zip(titles, line)) for line in rows]
|
||||
|
||||
def stream_expressions(expressions, data, kind, titles=None):
|
||||
codes = []
|
||||
for i, expr in enumerate(expressions):
|
||||
try:
|
||||
code = get_code(expr)
|
||||
except (TypeError, SyntaxError) as e:
|
||||
data = {
|
||||
'expr': expr,
|
||||
'error': unicode(e)
|
||||
}
|
||||
if titles:
|
||||
data['name'] = titles[i]
|
||||
else:
|
||||
data['idx'] = i
|
||||
raise APIError(u'invalid %s expression' % kind, data=data)
|
||||
codes.append((code, expr))
|
||||
for row in data:
|
||||
new_row = []
|
||||
row_vars = dict(row)
|
||||
row_vars['query'] = kwargs
|
||||
for i, (code, expr) in enumerate(codes):
|
||||
try:
|
||||
result = eval(code, {}, row_vars)
|
||||
except Exception as e:
|
||||
data = {
|
||||
'expr': expr,
|
||||
'row': repr(row),
|
||||
}
|
||||
if titles:
|
||||
data['name'] = titles[i]
|
||||
else:
|
||||
data['idx'] = i
|
||||
raise APIError(u'invalid %s expression' % kind, data=data)
|
||||
new_row.append(result)
|
||||
yield new_row, row
|
||||
|
||||
filters = query.get_list('filters')
|
||||
|
||||
if filters:
|
||||
data = [row for new_row, row in stream_expressions(filters, data, kind='filters')
|
||||
if all(new_row)]
|
||||
|
||||
order = query.get_list('order')
|
||||
if order:
|
||||
generator = stream_expressions(order, data, kind='order')
|
||||
new_data = [(tuple(new_row), row) for new_row, row in generator]
|
||||
new_data.sort(key=lambda (k, row): k)
|
||||
data = [row for key, row in new_data]
|
||||
|
||||
distinct = query.get_list('distinct')
|
||||
if distinct:
|
||||
generator = stream_expressions(distinct, data, kind='distinct')
|
||||
seen = set()
|
||||
new_data = []
|
||||
for new_row, row in generator:
|
||||
new_row = tuple(new_row)
|
||||
try:
|
||||
hash(new_row)
|
||||
except TypeError:
|
||||
raise APIError(u'distinct value is unhashable',
|
||||
data={
|
||||
'row': repr(row),
|
||||
'distinct': repr(new_row),
|
||||
})
|
||||
if new_row in seen:
|
||||
continue
|
||||
new_data.append(row)
|
||||
seen.add(new_row)
|
||||
data = new_data
|
||||
|
||||
projection = query.get_list('projections')
|
||||
if projection:
|
||||
expressions = []
|
||||
titles = []
|
||||
for mapping in projection:
|
||||
name, expr = mapping.split(':', 1)
|
||||
if not identifier_re.match(name):
|
||||
raise APIError(u'invalid projection name', data=name)
|
||||
titles.append(name)
|
||||
expressions.append(expr)
|
||||
new_data = []
|
||||
for new_row, row in stream_expressions(expressions, data, kind='projection',
|
||||
titles=titles):
|
||||
new_data.append(dict(zip(titles, new_row)))
|
||||
data = new_data
|
||||
|
||||
# allow jsonp queries by select2
|
||||
# filtering is done there afater projection because we need a projection named text for
|
||||
# retro-compatibility with previous use of the csvdatasource with select2
|
||||
if 'q' in request.GET:
|
||||
if 'case-insensitive' in request.GET:
|
||||
filters = ["query['q'].lower() in text.lower()"]
|
||||
else:
|
||||
filters = ["query['q'] in text"]
|
||||
data = [row for new_row, row in stream_expressions(filters, data, kind='filters')
|
||||
if new_row[0]]
|
||||
|
||||
if query.structure == 'array':
|
||||
return [[row[t] for t in titles] for row in data]
|
||||
elif query.structure == 'dict':
|
||||
return data
|
||||
elif query.structure == 'tuples':
|
||||
return [[[t, row[t]] for t in titles] for row in data]
|
||||
elif query.structure == 'onerow':
|
||||
if len(data) != 1:
|
||||
raise APIError('more or less than one row', data=data)
|
||||
return data[0]
|
||||
elif query.structure == 'one':
|
||||
if len(data) != 1:
|
||||
raise APIError('more or less than one row', data=data)
|
||||
if len(data[0]) != 1:
|
||||
raise APIError('more or less than one column', data=data)
|
||||
return data[0].values()[0]
|
|
@ -0,0 +1,84 @@
|
|||
{% extends "passerelle/manage/service_view.html" %}
|
||||
{% load i18n passerelle %}
|
||||
|
||||
{% block content %}
|
||||
{% if object.description %}{{object.description|linebreaks}}{% endif %}
|
||||
|
||||
<p>
|
||||
{% trans "File:" %}
|
||||
{% if object|can_edit:request.user %}<a href="{% url 'csv-download' connector_slug=object.slug %}">{{object.csv_file}}</a>
|
||||
{% else %}{{object.csv_file}}{% endif %}
|
||||
</p>
|
||||
|
||||
<div id="endpoints">
|
||||
<h3>{% trans 'Endpoints' %}</h3>
|
||||
<ul>
|
||||
<li>{% trans "Returning all file lines: "%}
|
||||
<a href="{% url "csvdatasource-data" slug=object.slug %}">{% url "csvdatasource-data" slug=object.slug %}</a>
|
||||
</li>
|
||||
<ul>
|
||||
<li>{% trans "Simple filter: returning lines containing 'abc' in 'text' column: "%}
|
||||
<a href="{% url "csvdatasource-data" slug=object.slug %}?q=abc">{% url "csvdatasource-data" slug=object.slug %}?q=abc</a>
|
||||
</li>
|
||||
<li>
|
||||
{% trans "Advanced filters: combination of column key name and filter." %}
|
||||
{% trans "Example:" %} <a href="{% url "csvdatasource-data" slug=object.slug %}?text__icontains=abc&id__gt=17">
|
||||
{% url "csvdatasource-data" slug=object.slug %}?text__icontains=abc&id__gt=17</a>
|
||||
<ul>
|
||||
<li><strong>contains</strong>: {%trans 'key name contains value'%}</li>
|
||||
<li><strong>icontains</strong>: {%trans 'key name contains value (insensitive)' %}</li>
|
||||
<li><strong>gt</strong>: {%trans 'key name greater than value'%}</li>
|
||||
<li><strong>ge</strong>: {%trans 'key name greater or equal to value'%}</li>
|
||||
<li><strong>lt</strong>: {%trans 'key name less than value'%}</li>
|
||||
<li><strong>le</strong>: {%trans 'key name less than or equal to value'%}</li>
|
||||
<li><strong>eq (=)</strong>: {%trans 'key name equal to value'%}</li>
|
||||
<li><strong>ieq (=)</strong>: {%trans 'key name equal to value (insensitive)'%}</li>
|
||||
<li><strong>ne</strong>: {%trans 'key name not equal to value'%}</li>
|
||||
<li><strong>ine</strong>: {%trans 'key name not equal to value (insensitive)'%}</li>
|
||||
</ul>
|
||||
<p>
|
||||
</li>
|
||||
</ul>
|
||||
{% for query in object.query_set.all %}
|
||||
<li>{{ query.label }}:
|
||||
<a href="{% url 'generic-endpoint' connector='csvdatasource' slug=object.slug endpoint='query' rest=query.slug %}/">{% url 'generic-endpoint' connector='csvdatasource' slug=object.slug endpoint='query' rest=query.slug %}/</a>
|
||||
{% if query.description %}— {{ query.description }}{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{% if object|can_edit:request.user %}
|
||||
<div id="queries">
|
||||
<h3>{% trans 'Queries' %}</h3>
|
||||
<div>
|
||||
{% if object.query_set.count %}
|
||||
<ul class="objects-list single-links">
|
||||
{% for query in object.query_set.all %}
|
||||
<li><a href="{% url 'csv-edit-query' connector_slug=object.slug pk=query.id %}">{{ query.slug }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p>{% trans 'No query are defined.' %}</p>
|
||||
{% endif %}
|
||||
<p>
|
||||
<a class="icon-plus button" href="{% url 'csv-new-query' connector_slug=object.slug %}">{% trans 'New Query' %}</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if perms.base.view_accessright %}
|
||||
<div id="security">
|
||||
<h3>{% trans "Security" %}</h3>
|
||||
<div>
|
||||
<p>
|
||||
{% trans 'Access is limited to the following API users:' %}
|
||||
</p>
|
||||
{% access_rights_table resource=object permission='can_access' %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% endblock %}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue