Commit 13644cc0 authored by Ulbrich, Christopher's avatar Ulbrich, Christopher
Browse files

project created without history

parents
# Config Files for Limit
config.yaml
config.yml
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# Environments
# .env
.env/
.venv/
env/
venv/
ENV/
env.bak/
venv.bak/
pythonenv*
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# operating system-related files
# file properties cache/storage on macOS
*.DS_Store
# thumbnail cache on Windows
Thumbs.db
# limit: the limesurvey interaction tool
_It's the CLI to glue things together using the LimeSurvey API_
## how to set up
- Open bash/terminal of your choice in the project main directory where the setup.py lives
- Activate your **venv** if you want/need:
```
virtualenv venv
source venv/bin/activate
```
You can leave your venv with just calling:
```
deactivate
```
- **Install** limit with:
```
pip install --editable .
```
- Use the _./limit/config.yml.example_ as template to create your **_./limit/config.yml_** and **edit it for your needs**.
- You can find the **standard Limesurvey API URL** in _'Global Settings > Interfaces'_
It's something like: [http://localhost/index.php/admin/remotecontrol](http://localhost/index.php/admin/remotecontrol)
- For the **extendRemoteControl API** you can find the URL in the plugin configuration page for the extendRemoteControl API. It's something like: [http://localhost/index.php/plugins/unsecure?plugin=extendRemoteControl&function=action](http://localhost/index.php/plugins/unsecure?plugin=extendRemoteControl&function=action)
## usage
- Run the cli by typing `limit` in the context you installed it in. This should show the usage hints.
- You can use the `--install-completion` option to set up completion for your shell
- You alwas have to specify the config environment to use ( :arrow_right: see first level of the YAML)
- Every function call starts a new session and closes it afterwards
- You can find all available API functions when calling the API URL in your browser (see above)
## usage examples
- Test API Setup:
```
limit start-session lsapi
```
should return:
> you have aquired a session key
- Set the global setting _'sitename'_
```
limit call-function lsapi set_site_settings sitename "My great Limesurvey"
```
## config file
- automatically uses first .yml or .yaml file in ./limit directory
- you can specify a config file from another location with the `--filepath` option
- a config file can contain configurations for multiple environments (first level of YAML, default: "lsapi")
## documentation of the functions:
Als entry point für __jede__ API Funktion wird jetzt `call-function` verwendet:
__required arguments:__
- configname , wenn filepath für config angegeben werden soll dann mit `--filepath`
- method so wie sie von der API spezifiziert ist also bspw. `set_site_settings` oder `add_user`
- (required) arguments für die API Funktion mehrteilige Namen/Strings mit "" begrenzen
- Es gibt keinen return Value, weil bisher nicht benötigt. Das Ergebnis des Calls wird ins Terminal geprintet
lsapi:
connection:
api-url: "http://localhost:8080/index.php/plugins/unsecure?plugin=extendRemoteControl&function=action"
user: "username"
password: "password"
#!/usr/bin/env python3
import os
import typer
import yaml
import requests
from typing import Optional
#import random
app = typer.Typer()
@app.command()
def main():
"""Welcome to LIMIT, the CLI tool to glue the LimeSurvey API to our processes!"""
#typer.echo("welcome to the limit")
pass
app()
@app.command()
def start_session(configname: str, filepath: Optional[str] = typer.Argument(None)):
"""This method first attains the configuration details and stores them, and uses them immidiately (if no error) for
geting a session key for the LimeSurvey JSON-RPC API , and stores it to use it for further API use
Argument: configname in the yaml, optional: path to config file if not in the working directory
TODO: add error handling
TODO: logging?
"""
if filepath is None:
for root, directories, file in os.walk(os.path.dirname(os.path.abspath(__file__))):
for fil in file:
if fil.endswith('.yml') or fil.endswith('.yaml'):
configContent = yaml.safe_load(
open(os.path.join(root, fil), 'r'))
os.environ['LSAPIURL'] = configContent.get(
configname).get('connection').get('api-url')
#print(os.environ.get('LSAPIURL'))
os.environ['LSAPIUSER'] = configContent.get(
configname).get('connection').get('user')
#print(os.environ.get('LSAPIUSER'))
os.environ['LSAPIPWD'] = configContent.get(
configname).get('connection').get('password')
#print(os.environ.get('LSAPIPWD'))
# config = configContent.get(configname).get('connection')
else:
configContent = yaml.safe_load(open(filepath))
os.environ['LSAPIURL'] = configContent.get(configname).get('connection').get('api-url')
#print(os.environ.get('LSAPIURL'))
os.environ['LSAPIUSER'] = configContent.get(configname).get('connection').get('user')
#print(os.environ.get('LSAPIUSER'))
os.environ['LSAPIPWD'] = configContent.get(configname).get('connection').get('password')
#print(os.environ.get('LSAPIPWD'))
payload_sesskey = {
'method': 'get_session_key',
'params': [os.environ.get('LSAPIUSER'), os.environ.get('LSAPIPWD')],
'plugin': 'Authdb',
'id': 1 # need the id for json decoding
}
response = requests.post(os.environ.get('LSAPIURL'), json=payload_sesskey, verify=False)
if response.json().get('result').startswith('result'):
print('Etwas ist schief gegangen bei der Anmeldung: ')
print(response.json())
# TODO: how to handle einen Abbruch, clean the envvars?
else:
print('you have aquired a session key')
os.environ['LSAPISESSKEY'] = response.json().get('result')
@app.command()
def release_session():
"""This method closes a connection, cleans session key
and cleans all other envvars
Returns:
[integer] : http status code #is this useful? or what is the use case
"""
payload_release = {
'method': 'release_session_key',
'params': [os.environ.get('LSAPISESSKEY')],
'id': 3
}
releasedSession = requests.post(
os.environ.get('LSAPIURL'), json=payload_release, verify=False).json()
os.environ.clear()
#return print(releasedSession)
@app.command()
def call_function(configname, functiontocall:str, functparams:list[str],filepath:str = None):
'''
Function to call API functions without having to specify them
'''
start_session(configname, filepath)
functparamsappended = list(functparams)
functparamsappended = [int(i) if i.isnumeric() else i for i in functparamsappended]
functparamsappended.insert(0,os.environ.get('LSAPISESSKEY'))
payload = {
}
payload['method'] = functiontocall
payload['params'] = functparamsappended
payload['id'] = 27
functValue = requests.post(os.environ.get('LSAPIURL'), json=payload, verify=False).json()
release_session()
typer.echo(functValue)
#@app.command()
def set_site_setting(SettingName, Value):
"""
Call the set_site_setting function specified als an api extension
Params:
SettingName : the setting that shall be set
Value : the new value for the specified setting
Returns:
string|array The requested value or an array with the error in case of error
"""
payload = {
'method': '',
'params': [os.environ.get('LSAPISESSKEY'), SettingName, Value],
'plugin': 'extendRemoteControl',
'id': 89
}
set_setting = requests.post(os.environ.get('LSAPIURL'), json=payload, verify=False).json()
return set_setting
#@app.command()
def add_user(UserName, FullName, UserMail, isSuperadmin=False):
"""
Params:
UserName: name of the new survey administrator
FullName: Full name of the new survey administrator
UserMail: Mail address of the new survey administrator
IsSuperadmin: Make the new survey administrator a Superadministrator, default = False
Return:
string|array The requested value or an array with the error in case of error
"""
payload = {
'method': 'add_user',
'params': [os.environ.get('LSAPISESSKEY'), UserName, FullName, UserMail, isSuperadmin],
'id': 12
}
added_user = requests.post(os.environ.get('LSAPIURL'), json=payload, verify=False)
return print(added_user)
#@app.command()
def get_pluginID(pluginName):
"""
Get PluginID
Function to get the ID of a plugin with a known name
params:
pluginName: name of the plugin
returns:
Requested value OR array with error
"""
payload = {
'method': 'get_plugin_id',
'params': [os.environ.get('LSAPISESSKEY'), pluginName],
'id': 91
}
pluginid = requests.post(os.environ.get('LSAPIURL'), json=payload, verify=False)
return print(pluginid)
#@app.command()
def get_plugin_config(pluginID):
"""
Get plugin configuration description
Function get plugin config parameter description for a plugin with a known ID
params:
pluginID: the pluginID for the plugin in question
returns:
Requested value OR array with error
"""
payload = {
'method': 'get_plugin_config',
'params': [os.environ.get('LSAPISESSKEY'), pluginID],
'id': 106
}
pluginConfig = requests.post(os.environ.get('LSAPIURL'), json=payload, verify=False)
return print(pluginConfig)
#@app.command()
def set_plugin_config(pluginName, configName, configValue):
"""
Function set plugin config values for a plugin with a known name
params:
pluginName: Name of the plugin to be searched
configName: Name of the configuration to be set
configValue: Value to be assigned to the config
returns:
Requested value OR array with error
"""
payload = {
'method': 'set_plugin_config',
'params': [os.environ.get('LSAPISESSKEY'), pluginName, configName, configValue],
'id': 46
}
setPluginConfig = requests.post(os.environ.get('LSAPIURL'), json=payload, verify=False)
return print(setPluginConfig)
#@app.command()
def add_Survey(SurveyID, SurveyTitle,language: Optional[str] = typer.Argument(None), surveyformat: Optional[str] = typer.Argument(None)):
"""
function add survey with minimal details, for now with German as default language and group by group view.
params:
SurveyID : specifies id for created survey
SurveyTitle : specifies title for created survey
returns:
surveyid OR error
"""
payload_emptysurvey = {
'method': 'add_survey',
'params': [os.environ.get('LSAPISESSKEY'), SurveyID, SurveyTitle, language, surveyformat],
'id': 5
}
emptySurvey = requests.post(
os.environ.get('LSAPIURL'), json=payload_emptysurvey, verify=False).json()
return print(emptySurvey)
if __name__ == "__main__":
app()
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
\ No newline at end of file
pyyaml==5.4.1
requests==2.25.1
typer==0.3.2
\ No newline at end of file
from setuptools import setup, find_packages
#zukünftig wird packaging eher durch einen Aufbau mit toml-file und setup.cfg unterstütz. Jedoch momentan wird --editable install nur mit setup.py unterstützt
def read_requirements():
with open('requirements.txt', 'r') as req:
content = req.read()
requirements = content.split('\n')
return requirements
setup(
name = 'limit',
version = '0.0.2',
packages = find_packages(),
include_package_data = True,
install_requires = read_requirements(),
entry_points="""
[console_scripts]
limit = limit.limit:main
"""
)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment