factpulse 1.0.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- factpulse/__init__.py +280 -0
- factpulse/api/__init__.py +13 -0
- factpulse/api/afnorpdppa_api.py +284 -0
- factpulse/api/afnorpdppa_directory_service_api.py +799 -0
- factpulse/api/afnorpdppa_flow_service_api.py +1075 -0
- factpulse/api/chorus_pro_api.py +4506 -0
- factpulse/api/processing_endpoints_unifis_api.py +592 -0
- factpulse/api/sant_api.py +281 -0
- factpulse/api/signature_lectronique_api.py +1358 -0
- factpulse/api/traitement_facture_api.py +3439 -0
- factpulse/api/utilisateur_api.py +282 -0
- factpulse/api_client.py +804 -0
- factpulse/api_response.py +21 -0
- factpulse/configuration.py +585 -0
- factpulse/exceptions.py +216 -0
- factpulse/models/__init__.py +124 -0
- factpulse/models/adresse_electronique.py +90 -0
- factpulse/models/adresse_postale.py +120 -0
- factpulse/models/body_ajouter_fichier_api_v1_chorus_pro_transverses_ajouter_fichier_post.py +104 -0
- factpulse/models/body_completer_facture_api_v1_chorus_pro_factures_completer_post.py +104 -0
- factpulse/models/body_lister_services_structure_api_v1_chorus_pro_structures_id_structure_cpp_services_get.py +102 -0
- factpulse/models/body_rechercher_factures_destinataire_api_v1_chorus_pro_factures_rechercher_destinataire_post.py +104 -0
- factpulse/models/body_rechercher_factures_fournisseur_api_v1_chorus_pro_factures_rechercher_fournisseur_post.py +104 -0
- factpulse/models/body_recycler_facture_api_v1_chorus_pro_factures_recycler_post.py +104 -0
- factpulse/models/body_telecharger_groupe_factures_api_v1_chorus_pro_factures_telecharger_groupe_post.py +104 -0
- factpulse/models/body_traiter_facture_recue_api_v1_chorus_pro_factures_traiter_facture_recue_post.py +104 -0
- factpulse/models/body_valideur_consulter_facture_api_v1_chorus_pro_factures_valideur_consulter_post.py +104 -0
- factpulse/models/body_valideur_rechercher_factures_api_v1_chorus_pro_factures_valideur_rechercher_post.py +104 -0
- factpulse/models/body_valideur_traiter_facture_api_v1_chorus_pro_factures_valideur_traiter_post.py +104 -0
- factpulse/models/cadre_de_facturation.py +102 -0
- factpulse/models/categorie_tva.py +44 -0
- factpulse/models/certificate_info_response.py +114 -0
- factpulse/models/chorus_pro_credentials.py +95 -0
- factpulse/models/code_cadre_facturation.py +39 -0
- factpulse/models/code_raison_reduction.py +42 -0
- factpulse/models/consulter_facture_request.py +98 -0
- factpulse/models/consulter_facture_response.py +142 -0
- factpulse/models/consulter_structure_request.py +100 -0
- factpulse/models/consulter_structure_response.py +142 -0
- factpulse/models/credentials_afnor.py +106 -0
- factpulse/models/credentials_chorus_pro.py +115 -0
- factpulse/models/destinataire.py +116 -0
- factpulse/models/destination.py +140 -0
- factpulse/models/destination_afnor.py +127 -0
- factpulse/models/destination_chorus_pro.py +108 -0
- factpulse/models/direction_flux.py +37 -0
- factpulse/models/donnees_facture_simplifiees.py +124 -0
- factpulse/models/facture_enrichie_info_input.py +123 -0
- factpulse/models/facture_enrichie_info_output.py +133 -0
- factpulse/models/facture_factur_x.py +173 -0
- factpulse/models/flux_resume.py +131 -0
- factpulse/models/format_sortie.py +37 -0
- factpulse/models/fournisseur.py +146 -0
- factpulse/models/generate_certificate_request.py +118 -0
- factpulse/models/generate_certificate_response.py +106 -0
- factpulse/models/http_validation_error.py +95 -0
- factpulse/models/information_signature_api.py +122 -0
- factpulse/models/ligne_de_poste.py +188 -0
- factpulse/models/ligne_de_poste_montant_remise_ht.py +145 -0
- factpulse/models/ligne_de_poste_montant_total_ligne_ht.py +145 -0
- factpulse/models/ligne_de_poste_taux_tva_manuel.py +145 -0
- factpulse/models/ligne_de_tva.py +118 -0
- factpulse/models/mode_depot.py +38 -0
- factpulse/models/mode_paiement.py +41 -0
- factpulse/models/montant_ht_total.py +139 -0
- factpulse/models/montant_total.py +138 -0
- factpulse/models/montant_total_acompte.py +145 -0
- factpulse/models/montant_total_montant_remise_globale_ttc.py +145 -0
- factpulse/models/montant_ttc_total.py +139 -0
- factpulse/models/montant_tva.py +139 -0
- factpulse/models/montantapayer.py +139 -0
- factpulse/models/montantbaseht.py +139 -0
- factpulse/models/montanthttotal.py +139 -0
- factpulse/models/montantttctotal.py +139 -0
- factpulse/models/montanttva.py +139 -0
- factpulse/models/montanttva1.py +139 -0
- factpulse/models/montantunitaireht.py +139 -0
- factpulse/models/obtenir_id_chorus_pro_request.py +100 -0
- factpulse/models/obtenir_id_chorus_pro_response.py +98 -0
- factpulse/models/options_processing.py +103 -0
- factpulse/models/parametres_signature.py +133 -0
- factpulse/models/parametres_structure.py +91 -0
- factpulse/models/pdf_factur_x_info.py +91 -0
- factpulse/models/pdp_credentials.py +93 -0
- factpulse/models/piece_jointe_complementaire.py +95 -0
- factpulse/models/profil_api.py +39 -0
- factpulse/models/profil_flux.py +38 -0
- factpulse/models/quantite.py +139 -0
- factpulse/models/quota_info.py +95 -0
- factpulse/models/rechercher_services_response.py +101 -0
- factpulse/models/rechercher_structure_request.py +119 -0
- factpulse/models/rechercher_structure_response.py +101 -0
- factpulse/models/references.py +124 -0
- factpulse/models/reponse_healthcheck_afnor.py +91 -0
- factpulse/models/reponse_recherche_flux.py +101 -0
- factpulse/models/reponse_soumission_flux.py +109 -0
- factpulse/models/reponse_tache.py +87 -0
- factpulse/models/reponse_validation_erreur.py +87 -0
- factpulse/models/reponse_validation_succes.py +87 -0
- factpulse/models/requete_recherche_flux.py +143 -0
- factpulse/models/requete_soumission_flux.py +123 -0
- factpulse/models/resultat_afnor.py +105 -0
- factpulse/models/resultat_chorus_pro.py +101 -0
- factpulse/models/resultat_validation_pdfapi.py +169 -0
- factpulse/models/scheme_id.py +40 -0
- factpulse/models/service_structure.py +93 -0
- factpulse/models/signature_info.py +101 -0
- factpulse/models/soumettre_facture_complete_request.py +116 -0
- factpulse/models/soumettre_facture_complete_response.py +145 -0
- factpulse/models/soumettre_facture_request.py +164 -0
- factpulse/models/soumettre_facture_response.py +103 -0
- factpulse/models/statut_acquittement.py +38 -0
- factpulse/models/statut_facture.py +96 -0
- factpulse/models/statut_tache.py +99 -0
- factpulse/models/structure_info.py +95 -0
- factpulse/models/syntaxe_flux.py +40 -0
- factpulse/models/tauxmanuel.py +139 -0
- factpulse/models/type_facture.py +37 -0
- factpulse/models/type_flux.py +40 -0
- factpulse/models/type_tva.py +39 -0
- factpulse/models/unite.py +41 -0
- factpulse/models/utilisateur.py +128 -0
- factpulse/models/validation_error.py +99 -0
- factpulse/models/validation_error_loc_inner.py +138 -0
- factpulse/py.typed +0 -0
- factpulse/rest.py +258 -0
- factpulse-1.0.6.dist-info/METADATA +182 -0
- factpulse-1.0.6.dist-info/RECORD +131 -0
- factpulse-1.0.6.dist-info/WHEEL +5 -0
- factpulse-1.0.6.dist-info/licenses/LICENSE +21 -0
- factpulse-1.0.6.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
API REST FactPulse
|
|
5
|
+
|
|
6
|
+
API REST pour la facturation électronique en France : Factur-X, AFNOR PDP/PA, signatures électroniques. ## 🎯 Fonctionnalités principales ### 📄 Génération de factures Factur-X - **Formats** : XML seul ou PDF/A-3 avec XML embarqué - **Profils** : MINIMUM, BASIC, EN16931, EXTENDED - **Normes** : EN 16931 (directive UE 2014/55), ISO 19005-3 (PDF/A-3), CII (UN/CEFACT) - **🆕 Format simplifié** : Génération à partir de SIRET + auto-enrichissement (API Chorus Pro + Recherche Entreprises) ### ✅ Validation et conformité - **Validation XML** : Schematron (45 à 210+ règles selon profil) - **Validation PDF** : PDF/A-3, métadonnées XMP Factur-X, signatures électroniques - **VeraPDF** : Validation stricte PDF/A (146+ règles ISO 19005-3) - **Traitement asynchrone** : Support Celery pour validations lourdes (VeraPDF) ### 📡 Intégration AFNOR PDP/PA (XP Z12-013) - **Soumission de flux** : Envoi de factures vers Plateformes de Dématérialisation Partenaires - **Recherche de flux** : Consultation des factures soumises - **Téléchargement** : Récupération des PDF/A-3 avec XML - **Directory Service** : Recherche d'entreprises (SIREN/SIRET) - **Multi-client** : Support de plusieurs configs PDP par utilisateur (stored credentials ou zero-storage) ### ✍️ Signature électronique PDF - **Standards** : PAdES-B-B, PAdES-B-T (horodatage RFC 3161), PAdES-B-LT (archivage long terme) - **Niveaux eIDAS** : SES (auto-signé), AdES (CA commerciale), QES (PSCO) - **Validation** : Vérification intégrité cryptographique et certificats - **Génération de certificats** : Certificats X.509 auto-signés pour tests ### 🔄 Traitement asynchrone - **Celery** : Génération, validation et signature asynchrones - **Polling** : Suivi d'état via `/taches/{id_tache}/statut` - **Pas de timeout** : Idéal pour gros fichiers ou validations lourdes ## 🔒 Authentification Toutes les requêtes nécessitent un **token JWT** dans le header Authorization : ``` Authorization: Bearer YOUR_JWT_TOKEN ``` ### Comment obtenir un token JWT ? #### 🔑 Méthode 1 : API `/api/token/` (Recommandée) **URL :** `https://www.factpulse.fr/api/token/` Cette méthode est **recommandée** pour l'intégration dans vos applications et workflows CI/CD. **Prérequis :** Avoir défini un mot de passe sur votre compte **Pour les utilisateurs inscrits via email/password :** - Vous avez déjà un mot de passe, utilisez-le directement **Pour les utilisateurs inscrits via OAuth (Google/GitHub) :** - Vous devez d'abord définir un mot de passe sur : https://www.factpulse.fr/accounts/password/set/ - Une fois le mot de passe créé, vous pourrez utiliser l'API **Exemple de requête :** ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\" }' ``` **Réponse :** ```json { \"access\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\", // Token d'accès (validité: 30 min) \"refresh\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\" // Token de rafraîchissement (validité: 7 jours) } ``` **Avantages :** - ✅ Automatisation complète (CI/CD, scripts) - ✅ Gestion programmatique des tokens - ✅ Support du refresh token pour renouveler automatiquement l'accès - ✅ Intégration facile dans n'importe quel langage/outil #### 🖥️ Méthode 2 : Génération via Dashboard (Alternative) **URL :** https://www.factpulse.fr/dashboard/ Cette méthode convient pour des tests rapides ou une utilisation occasionnelle via l'interface graphique. **Fonctionnement :** - Connectez-vous au dashboard - Utilisez les boutons \"Generate Test Token\" ou \"Generate Production Token\" - Fonctionne pour **tous** les utilisateurs (OAuth et email/password), sans nécessiter de mot de passe **Types de tokens :** - **Token Test** : Validité 24h, quota 1000 appels/jour (gratuit) - **Token Production** : Validité 7 jours, quota selon votre forfait **Avantages :** - ✅ Rapide pour tester l'API - ✅ Aucun mot de passe requis - ✅ Interface visuelle simple **Inconvénients :** - ❌ Nécessite une action manuelle - ❌ Pas de refresh token - ❌ Moins adapté pour l'automatisation ### 📚 Documentation complète Pour plus d'informations sur l'authentification et l'utilisation de l'API : https://www.factpulse.fr/documentation-api/
|
|
7
|
+
|
|
8
|
+
The version of the OpenAPI document: 1.0.0
|
|
9
|
+
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
|
10
|
+
|
|
11
|
+
Do not edit the class manually.
|
|
12
|
+
""" # noqa: E501
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
import pprint
|
|
17
|
+
import re # noqa: F401
|
|
18
|
+
import json
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr
|
|
21
|
+
from typing import Any, ClassVar, Dict, List, Optional
|
|
22
|
+
from factpulse.models.quota_info import QuotaInfo
|
|
23
|
+
from typing import Optional, Set
|
|
24
|
+
from typing_extensions import Self
|
|
25
|
+
|
|
26
|
+
class Utilisateur(BaseModel):
|
|
27
|
+
"""
|
|
28
|
+
Modèle Pydantic représentant les données de l'utilisateur authentifié.
|
|
29
|
+
""" # noqa: E501
|
|
30
|
+
id: StrictInt
|
|
31
|
+
username: StrictStr
|
|
32
|
+
email: StrictStr
|
|
33
|
+
is_active: StrictBool
|
|
34
|
+
is_superuser: Optional[StrictBool] = False
|
|
35
|
+
is_staff: Optional[StrictBool] = False
|
|
36
|
+
bypass_quota: Optional[StrictBool] = False
|
|
37
|
+
team_id: Optional[StrictInt] = None
|
|
38
|
+
has_quota: Optional[StrictBool] = True
|
|
39
|
+
quota_info: Optional[QuotaInfo] = None
|
|
40
|
+
is_trial: Optional[StrictBool] = False
|
|
41
|
+
client_uid: Optional[StrictStr] = None
|
|
42
|
+
__properties: ClassVar[List[str]] = ["id", "username", "email", "is_active", "is_superuser", "is_staff", "bypass_quota", "team_id", "has_quota", "quota_info", "is_trial", "client_uid"]
|
|
43
|
+
|
|
44
|
+
model_config = ConfigDict(
|
|
45
|
+
populate_by_name=True,
|
|
46
|
+
validate_assignment=True,
|
|
47
|
+
protected_namespaces=(),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def to_str(self) -> str:
|
|
52
|
+
"""Returns the string representation of the model using alias"""
|
|
53
|
+
return pprint.pformat(self.model_dump(by_alias=True))
|
|
54
|
+
|
|
55
|
+
def to_json(self) -> str:
|
|
56
|
+
"""Returns the JSON representation of the model using alias"""
|
|
57
|
+
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
|
|
58
|
+
return json.dumps(self.to_dict())
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def from_json(cls, json_str: str) -> Optional[Self]:
|
|
62
|
+
"""Create an instance of Utilisateur from a JSON string"""
|
|
63
|
+
return cls.from_dict(json.loads(json_str))
|
|
64
|
+
|
|
65
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
66
|
+
"""Return the dictionary representation of the model using alias.
|
|
67
|
+
|
|
68
|
+
This has the following differences from calling pydantic's
|
|
69
|
+
`self.model_dump(by_alias=True)`:
|
|
70
|
+
|
|
71
|
+
* `None` is only added to the output dict for nullable fields that
|
|
72
|
+
were set at model initialization. Other fields with value `None`
|
|
73
|
+
are ignored.
|
|
74
|
+
"""
|
|
75
|
+
excluded_fields: Set[str] = set([
|
|
76
|
+
])
|
|
77
|
+
|
|
78
|
+
_dict = self.model_dump(
|
|
79
|
+
by_alias=True,
|
|
80
|
+
exclude=excluded_fields,
|
|
81
|
+
exclude_none=True,
|
|
82
|
+
)
|
|
83
|
+
# override the default output from pydantic by calling `to_dict()` of quota_info
|
|
84
|
+
if self.quota_info:
|
|
85
|
+
_dict['quota_info'] = self.quota_info.to_dict()
|
|
86
|
+
# set to None if team_id (nullable) is None
|
|
87
|
+
# and model_fields_set contains the field
|
|
88
|
+
if self.team_id is None and "team_id" in self.model_fields_set:
|
|
89
|
+
_dict['team_id'] = None
|
|
90
|
+
|
|
91
|
+
# set to None if quota_info (nullable) is None
|
|
92
|
+
# and model_fields_set contains the field
|
|
93
|
+
if self.quota_info is None and "quota_info" in self.model_fields_set:
|
|
94
|
+
_dict['quota_info'] = None
|
|
95
|
+
|
|
96
|
+
# set to None if client_uid (nullable) is None
|
|
97
|
+
# and model_fields_set contains the field
|
|
98
|
+
if self.client_uid is None and "client_uid" in self.model_fields_set:
|
|
99
|
+
_dict['client_uid'] = None
|
|
100
|
+
|
|
101
|
+
return _dict
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
|
105
|
+
"""Create an instance of Utilisateur from a dict"""
|
|
106
|
+
if obj is None:
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
if not isinstance(obj, dict):
|
|
110
|
+
return cls.model_validate(obj)
|
|
111
|
+
|
|
112
|
+
_obj = cls.model_validate({
|
|
113
|
+
"id": obj.get("id"),
|
|
114
|
+
"username": obj.get("username"),
|
|
115
|
+
"email": obj.get("email"),
|
|
116
|
+
"is_active": obj.get("is_active"),
|
|
117
|
+
"is_superuser": obj.get("is_superuser") if obj.get("is_superuser") is not None else False,
|
|
118
|
+
"is_staff": obj.get("is_staff") if obj.get("is_staff") is not None else False,
|
|
119
|
+
"bypass_quota": obj.get("bypass_quota") if obj.get("bypass_quota") is not None else False,
|
|
120
|
+
"team_id": obj.get("team_id"),
|
|
121
|
+
"has_quota": obj.get("has_quota") if obj.get("has_quota") is not None else True,
|
|
122
|
+
"quota_info": QuotaInfo.from_dict(obj["quota_info"]) if obj.get("quota_info") is not None else None,
|
|
123
|
+
"is_trial": obj.get("is_trial") if obj.get("is_trial") is not None else False,
|
|
124
|
+
"client_uid": obj.get("client_uid")
|
|
125
|
+
})
|
|
126
|
+
return _obj
|
|
127
|
+
|
|
128
|
+
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
API REST FactPulse
|
|
5
|
+
|
|
6
|
+
API REST pour la facturation électronique en France : Factur-X, AFNOR PDP/PA, signatures électroniques. ## 🎯 Fonctionnalités principales ### 📄 Génération de factures Factur-X - **Formats** : XML seul ou PDF/A-3 avec XML embarqué - **Profils** : MINIMUM, BASIC, EN16931, EXTENDED - **Normes** : EN 16931 (directive UE 2014/55), ISO 19005-3 (PDF/A-3), CII (UN/CEFACT) - **🆕 Format simplifié** : Génération à partir de SIRET + auto-enrichissement (API Chorus Pro + Recherche Entreprises) ### ✅ Validation et conformité - **Validation XML** : Schematron (45 à 210+ règles selon profil) - **Validation PDF** : PDF/A-3, métadonnées XMP Factur-X, signatures électroniques - **VeraPDF** : Validation stricte PDF/A (146+ règles ISO 19005-3) - **Traitement asynchrone** : Support Celery pour validations lourdes (VeraPDF) ### 📡 Intégration AFNOR PDP/PA (XP Z12-013) - **Soumission de flux** : Envoi de factures vers Plateformes de Dématérialisation Partenaires - **Recherche de flux** : Consultation des factures soumises - **Téléchargement** : Récupération des PDF/A-3 avec XML - **Directory Service** : Recherche d'entreprises (SIREN/SIRET) - **Multi-client** : Support de plusieurs configs PDP par utilisateur (stored credentials ou zero-storage) ### ✍️ Signature électronique PDF - **Standards** : PAdES-B-B, PAdES-B-T (horodatage RFC 3161), PAdES-B-LT (archivage long terme) - **Niveaux eIDAS** : SES (auto-signé), AdES (CA commerciale), QES (PSCO) - **Validation** : Vérification intégrité cryptographique et certificats - **Génération de certificats** : Certificats X.509 auto-signés pour tests ### 🔄 Traitement asynchrone - **Celery** : Génération, validation et signature asynchrones - **Polling** : Suivi d'état via `/taches/{id_tache}/statut` - **Pas de timeout** : Idéal pour gros fichiers ou validations lourdes ## 🔒 Authentification Toutes les requêtes nécessitent un **token JWT** dans le header Authorization : ``` Authorization: Bearer YOUR_JWT_TOKEN ``` ### Comment obtenir un token JWT ? #### 🔑 Méthode 1 : API `/api/token/` (Recommandée) **URL :** `https://www.factpulse.fr/api/token/` Cette méthode est **recommandée** pour l'intégration dans vos applications et workflows CI/CD. **Prérequis :** Avoir défini un mot de passe sur votre compte **Pour les utilisateurs inscrits via email/password :** - Vous avez déjà un mot de passe, utilisez-le directement **Pour les utilisateurs inscrits via OAuth (Google/GitHub) :** - Vous devez d'abord définir un mot de passe sur : https://www.factpulse.fr/accounts/password/set/ - Une fois le mot de passe créé, vous pourrez utiliser l'API **Exemple de requête :** ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\" }' ``` **Réponse :** ```json { \"access\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\", // Token d'accès (validité: 30 min) \"refresh\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\" // Token de rafraîchissement (validité: 7 jours) } ``` **Avantages :** - ✅ Automatisation complète (CI/CD, scripts) - ✅ Gestion programmatique des tokens - ✅ Support du refresh token pour renouveler automatiquement l'accès - ✅ Intégration facile dans n'importe quel langage/outil #### 🖥️ Méthode 2 : Génération via Dashboard (Alternative) **URL :** https://www.factpulse.fr/dashboard/ Cette méthode convient pour des tests rapides ou une utilisation occasionnelle via l'interface graphique. **Fonctionnement :** - Connectez-vous au dashboard - Utilisez les boutons \"Generate Test Token\" ou \"Generate Production Token\" - Fonctionne pour **tous** les utilisateurs (OAuth et email/password), sans nécessiter de mot de passe **Types de tokens :** - **Token Test** : Validité 24h, quota 1000 appels/jour (gratuit) - **Token Production** : Validité 7 jours, quota selon votre forfait **Avantages :** - ✅ Rapide pour tester l'API - ✅ Aucun mot de passe requis - ✅ Interface visuelle simple **Inconvénients :** - ❌ Nécessite une action manuelle - ❌ Pas de refresh token - ❌ Moins adapté pour l'automatisation ### 📚 Documentation complète Pour plus d'informations sur l'authentification et l'utilisation de l'API : https://www.factpulse.fr/documentation-api/
|
|
7
|
+
|
|
8
|
+
The version of the OpenAPI document: 1.0.0
|
|
9
|
+
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
|
10
|
+
|
|
11
|
+
Do not edit the class manually.
|
|
12
|
+
""" # noqa: E501
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
import pprint
|
|
17
|
+
import re # noqa: F401
|
|
18
|
+
import json
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, ConfigDict, StrictStr
|
|
21
|
+
from typing import Any, ClassVar, Dict, List
|
|
22
|
+
from factpulse.models.validation_error_loc_inner import ValidationErrorLocInner
|
|
23
|
+
from typing import Optional, Set
|
|
24
|
+
from typing_extensions import Self
|
|
25
|
+
|
|
26
|
+
class ValidationError(BaseModel):
|
|
27
|
+
"""
|
|
28
|
+
ValidationError
|
|
29
|
+
""" # noqa: E501
|
|
30
|
+
loc: List[ValidationErrorLocInner]
|
|
31
|
+
msg: StrictStr
|
|
32
|
+
type: StrictStr
|
|
33
|
+
__properties: ClassVar[List[str]] = ["loc", "msg", "type"]
|
|
34
|
+
|
|
35
|
+
model_config = ConfigDict(
|
|
36
|
+
populate_by_name=True,
|
|
37
|
+
validate_assignment=True,
|
|
38
|
+
protected_namespaces=(),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def to_str(self) -> str:
|
|
43
|
+
"""Returns the string representation of the model using alias"""
|
|
44
|
+
return pprint.pformat(self.model_dump(by_alias=True))
|
|
45
|
+
|
|
46
|
+
def to_json(self) -> str:
|
|
47
|
+
"""Returns the JSON representation of the model using alias"""
|
|
48
|
+
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
|
|
49
|
+
return json.dumps(self.to_dict())
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_json(cls, json_str: str) -> Optional[Self]:
|
|
53
|
+
"""Create an instance of ValidationError from a JSON string"""
|
|
54
|
+
return cls.from_dict(json.loads(json_str))
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
57
|
+
"""Return the dictionary representation of the model using alias.
|
|
58
|
+
|
|
59
|
+
This has the following differences from calling pydantic's
|
|
60
|
+
`self.model_dump(by_alias=True)`:
|
|
61
|
+
|
|
62
|
+
* `None` is only added to the output dict for nullable fields that
|
|
63
|
+
were set at model initialization. Other fields with value `None`
|
|
64
|
+
are ignored.
|
|
65
|
+
"""
|
|
66
|
+
excluded_fields: Set[str] = set([
|
|
67
|
+
])
|
|
68
|
+
|
|
69
|
+
_dict = self.model_dump(
|
|
70
|
+
by_alias=True,
|
|
71
|
+
exclude=excluded_fields,
|
|
72
|
+
exclude_none=True,
|
|
73
|
+
)
|
|
74
|
+
# override the default output from pydantic by calling `to_dict()` of each item in loc (list)
|
|
75
|
+
_items = []
|
|
76
|
+
if self.loc:
|
|
77
|
+
for _item_loc in self.loc:
|
|
78
|
+
if _item_loc:
|
|
79
|
+
_items.append(_item_loc.to_dict())
|
|
80
|
+
_dict['loc'] = _items
|
|
81
|
+
return _dict
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
|
|
85
|
+
"""Create an instance of ValidationError from a dict"""
|
|
86
|
+
if obj is None:
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
if not isinstance(obj, dict):
|
|
90
|
+
return cls.model_validate(obj)
|
|
91
|
+
|
|
92
|
+
_obj = cls.model_validate({
|
|
93
|
+
"loc": [ValidationErrorLocInner.from_dict(_item) for _item in obj["loc"]] if obj.get("loc") is not None else None,
|
|
94
|
+
"msg": obj.get("msg"),
|
|
95
|
+
"type": obj.get("type")
|
|
96
|
+
})
|
|
97
|
+
return _obj
|
|
98
|
+
|
|
99
|
+
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
API REST FactPulse
|
|
5
|
+
|
|
6
|
+
API REST pour la facturation électronique en France : Factur-X, AFNOR PDP/PA, signatures électroniques. ## 🎯 Fonctionnalités principales ### 📄 Génération de factures Factur-X - **Formats** : XML seul ou PDF/A-3 avec XML embarqué - **Profils** : MINIMUM, BASIC, EN16931, EXTENDED - **Normes** : EN 16931 (directive UE 2014/55), ISO 19005-3 (PDF/A-3), CII (UN/CEFACT) - **🆕 Format simplifié** : Génération à partir de SIRET + auto-enrichissement (API Chorus Pro + Recherche Entreprises) ### ✅ Validation et conformité - **Validation XML** : Schematron (45 à 210+ règles selon profil) - **Validation PDF** : PDF/A-3, métadonnées XMP Factur-X, signatures électroniques - **VeraPDF** : Validation stricte PDF/A (146+ règles ISO 19005-3) - **Traitement asynchrone** : Support Celery pour validations lourdes (VeraPDF) ### 📡 Intégration AFNOR PDP/PA (XP Z12-013) - **Soumission de flux** : Envoi de factures vers Plateformes de Dématérialisation Partenaires - **Recherche de flux** : Consultation des factures soumises - **Téléchargement** : Récupération des PDF/A-3 avec XML - **Directory Service** : Recherche d'entreprises (SIREN/SIRET) - **Multi-client** : Support de plusieurs configs PDP par utilisateur (stored credentials ou zero-storage) ### ✍️ Signature électronique PDF - **Standards** : PAdES-B-B, PAdES-B-T (horodatage RFC 3161), PAdES-B-LT (archivage long terme) - **Niveaux eIDAS** : SES (auto-signé), AdES (CA commerciale), QES (PSCO) - **Validation** : Vérification intégrité cryptographique et certificats - **Génération de certificats** : Certificats X.509 auto-signés pour tests ### 🔄 Traitement asynchrone - **Celery** : Génération, validation et signature asynchrones - **Polling** : Suivi d'état via `/taches/{id_tache}/statut` - **Pas de timeout** : Idéal pour gros fichiers ou validations lourdes ## 🔒 Authentification Toutes les requêtes nécessitent un **token JWT** dans le header Authorization : ``` Authorization: Bearer YOUR_JWT_TOKEN ``` ### Comment obtenir un token JWT ? #### 🔑 Méthode 1 : API `/api/token/` (Recommandée) **URL :** `https://www.factpulse.fr/api/token/` Cette méthode est **recommandée** pour l'intégration dans vos applications et workflows CI/CD. **Prérequis :** Avoir défini un mot de passe sur votre compte **Pour les utilisateurs inscrits via email/password :** - Vous avez déjà un mot de passe, utilisez-le directement **Pour les utilisateurs inscrits via OAuth (Google/GitHub) :** - Vous devez d'abord définir un mot de passe sur : https://www.factpulse.fr/accounts/password/set/ - Une fois le mot de passe créé, vous pourrez utiliser l'API **Exemple de requête :** ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\" }' ``` **Réponse :** ```json { \"access\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\", // Token d'accès (validité: 30 min) \"refresh\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\" // Token de rafraîchissement (validité: 7 jours) } ``` **Avantages :** - ✅ Automatisation complète (CI/CD, scripts) - ✅ Gestion programmatique des tokens - ✅ Support du refresh token pour renouveler automatiquement l'accès - ✅ Intégration facile dans n'importe quel langage/outil #### 🖥️ Méthode 2 : Génération via Dashboard (Alternative) **URL :** https://www.factpulse.fr/dashboard/ Cette méthode convient pour des tests rapides ou une utilisation occasionnelle via l'interface graphique. **Fonctionnement :** - Connectez-vous au dashboard - Utilisez les boutons \"Generate Test Token\" ou \"Generate Production Token\" - Fonctionne pour **tous** les utilisateurs (OAuth et email/password), sans nécessiter de mot de passe **Types de tokens :** - **Token Test** : Validité 24h, quota 1000 appels/jour (gratuit) - **Token Production** : Validité 7 jours, quota selon votre forfait **Avantages :** - ✅ Rapide pour tester l'API - ✅ Aucun mot de passe requis - ✅ Interface visuelle simple **Inconvénients :** - ❌ Nécessite une action manuelle - ❌ Pas de refresh token - ❌ Moins adapté pour l'automatisation ### 📚 Documentation complète Pour plus d'informations sur l'authentification et l'utilisation de l'API : https://www.factpulse.fr/documentation-api/
|
|
7
|
+
|
|
8
|
+
The version of the OpenAPI document: 1.0.0
|
|
9
|
+
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
|
10
|
+
|
|
11
|
+
Do not edit the class manually.
|
|
12
|
+
""" # noqa: E501
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
from inspect import getfullargspec
|
|
17
|
+
import json
|
|
18
|
+
import pprint
|
|
19
|
+
import re # noqa: F401
|
|
20
|
+
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator
|
|
21
|
+
from typing import Optional
|
|
22
|
+
from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict
|
|
23
|
+
from typing_extensions import Literal, Self
|
|
24
|
+
from pydantic import Field
|
|
25
|
+
|
|
26
|
+
VALIDATIONERRORLOCINNER_ANY_OF_SCHEMAS = ["int", "str"]
|
|
27
|
+
|
|
28
|
+
class ValidationErrorLocInner(BaseModel):
|
|
29
|
+
"""
|
|
30
|
+
ValidationErrorLocInner
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
# data type: str
|
|
34
|
+
anyof_schema_1_validator: Optional[StrictStr] = None
|
|
35
|
+
# data type: int
|
|
36
|
+
anyof_schema_2_validator: Optional[StrictInt] = None
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
actual_instance: Optional[Union[int, str]] = None
|
|
39
|
+
else:
|
|
40
|
+
actual_instance: Any = None
|
|
41
|
+
any_of_schemas: Set[str] = { "int", "str" }
|
|
42
|
+
|
|
43
|
+
model_config = {
|
|
44
|
+
"validate_assignment": True,
|
|
45
|
+
"protected_namespaces": (),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
def __init__(self, *args, **kwargs) -> None:
|
|
49
|
+
if args:
|
|
50
|
+
if len(args) > 1:
|
|
51
|
+
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
|
|
52
|
+
if kwargs:
|
|
53
|
+
raise ValueError("If a position argument is used, keyword arguments cannot be used.")
|
|
54
|
+
super().__init__(actual_instance=args[0])
|
|
55
|
+
else:
|
|
56
|
+
super().__init__(**kwargs)
|
|
57
|
+
|
|
58
|
+
@field_validator('actual_instance')
|
|
59
|
+
def actual_instance_must_validate_anyof(cls, v):
|
|
60
|
+
instance = ValidationErrorLocInner.model_construct()
|
|
61
|
+
error_messages = []
|
|
62
|
+
# validate data type: str
|
|
63
|
+
try:
|
|
64
|
+
instance.anyof_schema_1_validator = v
|
|
65
|
+
return v
|
|
66
|
+
except (ValidationError, ValueError) as e:
|
|
67
|
+
error_messages.append(str(e))
|
|
68
|
+
# validate data type: int
|
|
69
|
+
try:
|
|
70
|
+
instance.anyof_schema_2_validator = v
|
|
71
|
+
return v
|
|
72
|
+
except (ValidationError, ValueError) as e:
|
|
73
|
+
error_messages.append(str(e))
|
|
74
|
+
if error_messages:
|
|
75
|
+
# no match
|
|
76
|
+
raise ValueError("No match found when setting the actual_instance in ValidationErrorLocInner with anyOf schemas: int, str. Details: " + ", ".join(error_messages))
|
|
77
|
+
else:
|
|
78
|
+
return v
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def from_dict(cls, obj: Dict[str, Any]) -> Self:
|
|
82
|
+
return cls.from_json(json.dumps(obj))
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def from_json(cls, json_str: str) -> Self:
|
|
86
|
+
"""Returns the object represented by the json string"""
|
|
87
|
+
instance = cls.model_construct()
|
|
88
|
+
error_messages = []
|
|
89
|
+
# deserialize data into str
|
|
90
|
+
try:
|
|
91
|
+
# validation
|
|
92
|
+
instance.anyof_schema_1_validator = json.loads(json_str)
|
|
93
|
+
# assign value to actual_instance
|
|
94
|
+
instance.actual_instance = instance.anyof_schema_1_validator
|
|
95
|
+
return instance
|
|
96
|
+
except (ValidationError, ValueError) as e:
|
|
97
|
+
error_messages.append(str(e))
|
|
98
|
+
# deserialize data into int
|
|
99
|
+
try:
|
|
100
|
+
# validation
|
|
101
|
+
instance.anyof_schema_2_validator = json.loads(json_str)
|
|
102
|
+
# assign value to actual_instance
|
|
103
|
+
instance.actual_instance = instance.anyof_schema_2_validator
|
|
104
|
+
return instance
|
|
105
|
+
except (ValidationError, ValueError) as e:
|
|
106
|
+
error_messages.append(str(e))
|
|
107
|
+
|
|
108
|
+
if error_messages:
|
|
109
|
+
# no match
|
|
110
|
+
raise ValueError("No match found when deserializing the JSON string into ValidationErrorLocInner with anyOf schemas: int, str. Details: " + ", ".join(error_messages))
|
|
111
|
+
else:
|
|
112
|
+
return instance
|
|
113
|
+
|
|
114
|
+
def to_json(self) -> str:
|
|
115
|
+
"""Returns the JSON representation of the actual instance"""
|
|
116
|
+
if self.actual_instance is None:
|
|
117
|
+
return "null"
|
|
118
|
+
|
|
119
|
+
if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json):
|
|
120
|
+
return self.actual_instance.to_json()
|
|
121
|
+
else:
|
|
122
|
+
return json.dumps(self.actual_instance)
|
|
123
|
+
|
|
124
|
+
def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]:
|
|
125
|
+
"""Returns the dict representation of the actual instance"""
|
|
126
|
+
if self.actual_instance is None:
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict):
|
|
130
|
+
return self.actual_instance.to_dict()
|
|
131
|
+
else:
|
|
132
|
+
return self.actual_instance
|
|
133
|
+
|
|
134
|
+
def to_str(self) -> str:
|
|
135
|
+
"""Returns the string representation of the actual instance"""
|
|
136
|
+
return pprint.pformat(self.model_dump())
|
|
137
|
+
|
|
138
|
+
|
factpulse/py.typed
ADDED
|
File without changes
|
factpulse/rest.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
API REST FactPulse
|
|
5
|
+
|
|
6
|
+
API REST pour la facturation électronique en France : Factur-X, AFNOR PDP/PA, signatures électroniques. ## 🎯 Fonctionnalités principales ### 📄 Génération de factures Factur-X - **Formats** : XML seul ou PDF/A-3 avec XML embarqué - **Profils** : MINIMUM, BASIC, EN16931, EXTENDED - **Normes** : EN 16931 (directive UE 2014/55), ISO 19005-3 (PDF/A-3), CII (UN/CEFACT) - **🆕 Format simplifié** : Génération à partir de SIRET + auto-enrichissement (API Chorus Pro + Recherche Entreprises) ### ✅ Validation et conformité - **Validation XML** : Schematron (45 à 210+ règles selon profil) - **Validation PDF** : PDF/A-3, métadonnées XMP Factur-X, signatures électroniques - **VeraPDF** : Validation stricte PDF/A (146+ règles ISO 19005-3) - **Traitement asynchrone** : Support Celery pour validations lourdes (VeraPDF) ### 📡 Intégration AFNOR PDP/PA (XP Z12-013) - **Soumission de flux** : Envoi de factures vers Plateformes de Dématérialisation Partenaires - **Recherche de flux** : Consultation des factures soumises - **Téléchargement** : Récupération des PDF/A-3 avec XML - **Directory Service** : Recherche d'entreprises (SIREN/SIRET) - **Multi-client** : Support de plusieurs configs PDP par utilisateur (stored credentials ou zero-storage) ### ✍️ Signature électronique PDF - **Standards** : PAdES-B-B, PAdES-B-T (horodatage RFC 3161), PAdES-B-LT (archivage long terme) - **Niveaux eIDAS** : SES (auto-signé), AdES (CA commerciale), QES (PSCO) - **Validation** : Vérification intégrité cryptographique et certificats - **Génération de certificats** : Certificats X.509 auto-signés pour tests ### 🔄 Traitement asynchrone - **Celery** : Génération, validation et signature asynchrones - **Polling** : Suivi d'état via `/taches/{id_tache}/statut` - **Pas de timeout** : Idéal pour gros fichiers ou validations lourdes ## 🔒 Authentification Toutes les requêtes nécessitent un **token JWT** dans le header Authorization : ``` Authorization: Bearer YOUR_JWT_TOKEN ``` ### Comment obtenir un token JWT ? #### 🔑 Méthode 1 : API `/api/token/` (Recommandée) **URL :** `https://www.factpulse.fr/api/token/` Cette méthode est **recommandée** pour l'intégration dans vos applications et workflows CI/CD. **Prérequis :** Avoir défini un mot de passe sur votre compte **Pour les utilisateurs inscrits via email/password :** - Vous avez déjà un mot de passe, utilisez-le directement **Pour les utilisateurs inscrits via OAuth (Google/GitHub) :** - Vous devez d'abord définir un mot de passe sur : https://www.factpulse.fr/accounts/password/set/ - Une fois le mot de passe créé, vous pourrez utiliser l'API **Exemple de requête :** ```bash curl -X POST https://www.factpulse.fr/api/token/ \\ -H \"Content-Type: application/json\" \\ -d '{ \"username\": \"votre_email@example.com\", \"password\": \"votre_mot_de_passe\" }' ``` **Réponse :** ```json { \"access\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\", // Token d'accès (validité: 30 min) \"refresh\": \"eyJ0eXAiOiJKV1QiLCJhbGc...\" // Token de rafraîchissement (validité: 7 jours) } ``` **Avantages :** - ✅ Automatisation complète (CI/CD, scripts) - ✅ Gestion programmatique des tokens - ✅ Support du refresh token pour renouveler automatiquement l'accès - ✅ Intégration facile dans n'importe quel langage/outil #### 🖥️ Méthode 2 : Génération via Dashboard (Alternative) **URL :** https://www.factpulse.fr/dashboard/ Cette méthode convient pour des tests rapides ou une utilisation occasionnelle via l'interface graphique. **Fonctionnement :** - Connectez-vous au dashboard - Utilisez les boutons \"Generate Test Token\" ou \"Generate Production Token\" - Fonctionne pour **tous** les utilisateurs (OAuth et email/password), sans nécessiter de mot de passe **Types de tokens :** - **Token Test** : Validité 24h, quota 1000 appels/jour (gratuit) - **Token Production** : Validité 7 jours, quota selon votre forfait **Avantages :** - ✅ Rapide pour tester l'API - ✅ Aucun mot de passe requis - ✅ Interface visuelle simple **Inconvénients :** - ❌ Nécessite une action manuelle - ❌ Pas de refresh token - ❌ Moins adapté pour l'automatisation ### 📚 Documentation complète Pour plus d'informations sur l'authentification et l'utilisation de l'API : https://www.factpulse.fr/documentation-api/
|
|
7
|
+
|
|
8
|
+
The version of the OpenAPI document: 1.0.0
|
|
9
|
+
Generated by OpenAPI Generator (https://openapi-generator.tech)
|
|
10
|
+
|
|
11
|
+
Do not edit the class manually.
|
|
12
|
+
""" # noqa: E501
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
import io
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import ssl
|
|
19
|
+
|
|
20
|
+
import urllib3
|
|
21
|
+
|
|
22
|
+
from factpulse.exceptions import ApiException, ApiValueError
|
|
23
|
+
|
|
24
|
+
SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"}
|
|
25
|
+
RESTResponseType = urllib3.HTTPResponse
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_socks_proxy_url(url):
|
|
29
|
+
if url is None:
|
|
30
|
+
return False
|
|
31
|
+
split_section = url.split("://")
|
|
32
|
+
if len(split_section) < 2:
|
|
33
|
+
return False
|
|
34
|
+
else:
|
|
35
|
+
return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RESTResponse(io.IOBase):
|
|
39
|
+
|
|
40
|
+
def __init__(self, resp) -> None:
|
|
41
|
+
self.response = resp
|
|
42
|
+
self.status = resp.status
|
|
43
|
+
self.reason = resp.reason
|
|
44
|
+
self.data = None
|
|
45
|
+
|
|
46
|
+
def read(self):
|
|
47
|
+
if self.data is None:
|
|
48
|
+
self.data = self.response.data
|
|
49
|
+
return self.data
|
|
50
|
+
|
|
51
|
+
def getheaders(self):
|
|
52
|
+
"""Returns a dictionary of the response headers."""
|
|
53
|
+
return self.response.headers
|
|
54
|
+
|
|
55
|
+
def getheader(self, name, default=None):
|
|
56
|
+
"""Returns a given response header."""
|
|
57
|
+
return self.response.headers.get(name, default)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class RESTClientObject:
|
|
61
|
+
|
|
62
|
+
def __init__(self, configuration) -> None:
|
|
63
|
+
# urllib3.PoolManager will pass all kw parameters to connectionpool
|
|
64
|
+
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501
|
|
65
|
+
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501
|
|
66
|
+
# Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501
|
|
67
|
+
|
|
68
|
+
# cert_reqs
|
|
69
|
+
if configuration.verify_ssl:
|
|
70
|
+
cert_reqs = ssl.CERT_REQUIRED
|
|
71
|
+
else:
|
|
72
|
+
cert_reqs = ssl.CERT_NONE
|
|
73
|
+
|
|
74
|
+
pool_args = {
|
|
75
|
+
"cert_reqs": cert_reqs,
|
|
76
|
+
"ca_certs": configuration.ssl_ca_cert,
|
|
77
|
+
"cert_file": configuration.cert_file,
|
|
78
|
+
"key_file": configuration.key_file,
|
|
79
|
+
"ca_cert_data": configuration.ca_cert_data,
|
|
80
|
+
}
|
|
81
|
+
if configuration.assert_hostname is not None:
|
|
82
|
+
pool_args['assert_hostname'] = (
|
|
83
|
+
configuration.assert_hostname
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
if configuration.retries is not None:
|
|
87
|
+
pool_args['retries'] = configuration.retries
|
|
88
|
+
|
|
89
|
+
if configuration.tls_server_name:
|
|
90
|
+
pool_args['server_hostname'] = configuration.tls_server_name
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
if configuration.socket_options is not None:
|
|
94
|
+
pool_args['socket_options'] = configuration.socket_options
|
|
95
|
+
|
|
96
|
+
if configuration.connection_pool_maxsize is not None:
|
|
97
|
+
pool_args['maxsize'] = configuration.connection_pool_maxsize
|
|
98
|
+
|
|
99
|
+
# https pool manager
|
|
100
|
+
self.pool_manager: urllib3.PoolManager
|
|
101
|
+
|
|
102
|
+
if configuration.proxy:
|
|
103
|
+
if is_socks_proxy_url(configuration.proxy):
|
|
104
|
+
from urllib3.contrib.socks import SOCKSProxyManager
|
|
105
|
+
pool_args["proxy_url"] = configuration.proxy
|
|
106
|
+
pool_args["headers"] = configuration.proxy_headers
|
|
107
|
+
self.pool_manager = SOCKSProxyManager(**pool_args)
|
|
108
|
+
else:
|
|
109
|
+
pool_args["proxy_url"] = configuration.proxy
|
|
110
|
+
pool_args["proxy_headers"] = configuration.proxy_headers
|
|
111
|
+
self.pool_manager = urllib3.ProxyManager(**pool_args)
|
|
112
|
+
else:
|
|
113
|
+
self.pool_manager = urllib3.PoolManager(**pool_args)
|
|
114
|
+
|
|
115
|
+
def request(
|
|
116
|
+
self,
|
|
117
|
+
method,
|
|
118
|
+
url,
|
|
119
|
+
headers=None,
|
|
120
|
+
body=None,
|
|
121
|
+
post_params=None,
|
|
122
|
+
_request_timeout=None
|
|
123
|
+
):
|
|
124
|
+
"""Perform requests.
|
|
125
|
+
|
|
126
|
+
:param method: http request method
|
|
127
|
+
:param url: http request url
|
|
128
|
+
:param headers: http request headers
|
|
129
|
+
:param body: request json body, for `application/json`
|
|
130
|
+
:param post_params: request post parameters,
|
|
131
|
+
`application/x-www-form-urlencoded`
|
|
132
|
+
and `multipart/form-data`
|
|
133
|
+
:param _request_timeout: timeout setting for this request. If one
|
|
134
|
+
number provided, it will be total request
|
|
135
|
+
timeout. It can also be a pair (tuple) of
|
|
136
|
+
(connection, read) timeouts.
|
|
137
|
+
"""
|
|
138
|
+
method = method.upper()
|
|
139
|
+
assert method in [
|
|
140
|
+
'GET',
|
|
141
|
+
'HEAD',
|
|
142
|
+
'DELETE',
|
|
143
|
+
'POST',
|
|
144
|
+
'PUT',
|
|
145
|
+
'PATCH',
|
|
146
|
+
'OPTIONS'
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
if post_params and body:
|
|
150
|
+
raise ApiValueError(
|
|
151
|
+
"body parameter cannot be used with post_params parameter."
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
post_params = post_params or {}
|
|
155
|
+
headers = headers or {}
|
|
156
|
+
|
|
157
|
+
timeout = None
|
|
158
|
+
if _request_timeout:
|
|
159
|
+
if isinstance(_request_timeout, (int, float)):
|
|
160
|
+
timeout = urllib3.Timeout(total=_request_timeout)
|
|
161
|
+
elif (
|
|
162
|
+
isinstance(_request_timeout, tuple)
|
|
163
|
+
and len(_request_timeout) == 2
|
|
164
|
+
):
|
|
165
|
+
timeout = urllib3.Timeout(
|
|
166
|
+
connect=_request_timeout[0],
|
|
167
|
+
read=_request_timeout[1]
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
|
|
172
|
+
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
|
|
173
|
+
|
|
174
|
+
# no content type provided or payload is json
|
|
175
|
+
content_type = headers.get('Content-Type')
|
|
176
|
+
if (
|
|
177
|
+
not content_type
|
|
178
|
+
or re.search('json', content_type, re.IGNORECASE)
|
|
179
|
+
):
|
|
180
|
+
request_body = None
|
|
181
|
+
if body is not None:
|
|
182
|
+
request_body = json.dumps(body)
|
|
183
|
+
r = self.pool_manager.request(
|
|
184
|
+
method,
|
|
185
|
+
url,
|
|
186
|
+
body=request_body,
|
|
187
|
+
timeout=timeout,
|
|
188
|
+
headers=headers,
|
|
189
|
+
preload_content=False
|
|
190
|
+
)
|
|
191
|
+
elif content_type == 'application/x-www-form-urlencoded':
|
|
192
|
+
r = self.pool_manager.request(
|
|
193
|
+
method,
|
|
194
|
+
url,
|
|
195
|
+
fields=post_params,
|
|
196
|
+
encode_multipart=False,
|
|
197
|
+
timeout=timeout,
|
|
198
|
+
headers=headers,
|
|
199
|
+
preload_content=False
|
|
200
|
+
)
|
|
201
|
+
elif content_type == 'multipart/form-data':
|
|
202
|
+
# must del headers['Content-Type'], or the correct
|
|
203
|
+
# Content-Type which generated by urllib3 will be
|
|
204
|
+
# overwritten.
|
|
205
|
+
del headers['Content-Type']
|
|
206
|
+
# Ensures that dict objects are serialized
|
|
207
|
+
post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
|
|
208
|
+
r = self.pool_manager.request(
|
|
209
|
+
method,
|
|
210
|
+
url,
|
|
211
|
+
fields=post_params,
|
|
212
|
+
encode_multipart=True,
|
|
213
|
+
timeout=timeout,
|
|
214
|
+
headers=headers,
|
|
215
|
+
preload_content=False
|
|
216
|
+
)
|
|
217
|
+
# Pass a `string` parameter directly in the body to support
|
|
218
|
+
# other content types than JSON when `body` argument is
|
|
219
|
+
# provided in serialized form.
|
|
220
|
+
elif isinstance(body, str) or isinstance(body, bytes):
|
|
221
|
+
r = self.pool_manager.request(
|
|
222
|
+
method,
|
|
223
|
+
url,
|
|
224
|
+
body=body,
|
|
225
|
+
timeout=timeout,
|
|
226
|
+
headers=headers,
|
|
227
|
+
preload_content=False
|
|
228
|
+
)
|
|
229
|
+
elif headers['Content-Type'].startswith('text/') and isinstance(body, bool):
|
|
230
|
+
request_body = "true" if body else "false"
|
|
231
|
+
r = self.pool_manager.request(
|
|
232
|
+
method,
|
|
233
|
+
url,
|
|
234
|
+
body=request_body,
|
|
235
|
+
preload_content=False,
|
|
236
|
+
timeout=timeout,
|
|
237
|
+
headers=headers)
|
|
238
|
+
else:
|
|
239
|
+
# Cannot generate the request from given parameters
|
|
240
|
+
msg = """Cannot prepare a request message for provided
|
|
241
|
+
arguments. Please check that your arguments match
|
|
242
|
+
declared content type."""
|
|
243
|
+
raise ApiException(status=0, reason=msg)
|
|
244
|
+
# For `GET`, `HEAD`
|
|
245
|
+
else:
|
|
246
|
+
r = self.pool_manager.request(
|
|
247
|
+
method,
|
|
248
|
+
url,
|
|
249
|
+
fields={},
|
|
250
|
+
timeout=timeout,
|
|
251
|
+
headers=headers,
|
|
252
|
+
preload_content=False
|
|
253
|
+
)
|
|
254
|
+
except urllib3.exceptions.SSLError as e:
|
|
255
|
+
msg = "\n".join([type(e).__name__, str(e)])
|
|
256
|
+
raise ApiException(status=0, reason=msg)
|
|
257
|
+
|
|
258
|
+
return RESTResponse(r)
|