From a132d59c70e7fb5f9b6ebc19614a7e66ed7523b7 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Wed, 25 May 2022 16:36:17 -0400 Subject: [PATCH 01/13] Added pylint config for CI --- demo/graphtutorial/main.py | 7 +- demo/graphtutorial/pylintrc | 579 ++++++++++++++++++++++++++++++++++++ 2 files changed, 582 insertions(+), 4 deletions(-) create mode 100644 demo/graphtutorial/pylintrc diff --git a/demo/graphtutorial/main.py b/demo/graphtutorial/main.py index b476780..ea15be4 100644 --- a/demo/graphtutorial/main.py +++ b/demo/graphtutorial/main.py @@ -11,9 +11,9 @@ def main(): # Load settings config = configparser.ConfigParser() config.read(['config.cfg', 'config.dev.cfg']) - azureSettings = config['azure'] + azure_settings = config['azure'] - initialize_graph(azureSettings) + initialize_graph(azure_settings) greet_user() @@ -30,7 +30,7 @@ def main(): try: choice = int(input()) - except: + except ValueError: choice = -1 if choice == 0: @@ -94,7 +94,6 @@ def send_mail(): graph.send_mail('Testing Microsoft Graph', 'Hello world!', user_email) print('Mail sent.\n') - return # # diff --git a/demo/graphtutorial/pylintrc b/demo/graphtutorial/pylintrc new file mode 100644 index 0000000..77936bd --- /dev/null +++ b/demo/graphtutorial/pylintrc @@ -0,0 +1,579 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=10.0 + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against paths and can be in Posix or Windows format. +ignore-paths= + +# Files or directories matching the regex patterns are skipped. The regex +# matches against base names, not paths. The default value ignores emacs file +# locks +ignore-patterns=^\.# + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.10 + +# Discover python modules and packages in the file system subtree. +recursive=yes + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=C0114, + C0116 + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +#notes-rgx= + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear and the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# class is considered mixin if its name matches the mixin-class-rgx option. +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins ignore-mixin- +# members is set to 'yes' +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=no + +# Signatures are removed from the similarity computation +ignore-signatures=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception From b3a5bc44c4d1860ef3e687a945b806c4573dab80 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 08:42:30 -0400 Subject: [PATCH 02/13] Create pylint.yml --- .github/workflows/pylint.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .github/workflows/pylint.yml diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml new file mode 100644 index 0000000..a546d37 --- /dev/null +++ b/.github/workflows/pylint.yml @@ -0,0 +1,28 @@ +name: Pylint + +on: [push] + +jobs: + build: + defaults: + run: + working-directory: demo/graphtutorial + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.8", "3.9", "3.10"] + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install pylint + - name: Analysing the code with pylint + run: | + pylint $(git ls-files '*.py') From be1c0b14d481991caf0e4613a3dc4ca9ccf1a570 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 11:41:08 -0400 Subject: [PATCH 03/13] Converted graph module to a class --- demo/graphtutorial/graph.py | 211 ++++++++++++++++++------------------ demo/graphtutorial/main.py | 33 +++--- 2 files changed, 119 insertions(+), 125 deletions(-) diff --git a/demo/graphtutorial/graph.py b/demo/graphtutorial/graph.py index 13a1938..58148ad 100644 --- a/demo/graphtutorial/graph.py +++ b/demo/graphtutorial/graph.py @@ -2,119 +2,118 @@ # Licensed under the MIT License. # -import sys import json +from configparser import SectionProxy from azure.identity import DeviceCodeCredential, ClientSecretCredential from msgraph.core import GraphClient -# Assign variables to the module so they stay set -this = sys.modules[__name__] +class Graph: -def initialize_graph_for_user_auth(config): - this.settings = config - client_id = this.settings['clientId'] - tenant_id = this.settings['authTenant'] - graph_scopes = this.settings['graphUserScopes'].split(' ') + def __init__(self, config: SectionProxy): + self.settings: SectionProxy = config + client_id = self.settings['clientId'] + tenant_id = self.settings['authTenant'] + graph_scopes = self.settings['graphUserScopes'].split(' ') - this.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id) - this.user_client = GraphClient(credential=this.device_code_credential, scopes=graph_scopes) + self.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id) + self.user_client = GraphClient(credential=self.device_code_credential, scopes=graph_scopes) # -# -def get_user_token(): - graph_scopes = this.settings['graphUserScopes'] - access_token = this.device_code_credential.get_token(graph_scopes) - return access_token.token -# - -# -def get_user(): - endpoint = '/me' - # Only request specific properties - select = 'displayName,mail,userPrincipalName' - request_url = f'{endpoint}?$select={select}' - - user_response = this.user_client.get(request_url) - return user_response.json() -# - -# -def get_inbox(): - endpoint = '/me/mailFolders/inbox/messages' - # Only request specific properties - select = 'from,isRead,receivedDateTime,subject' - # Get at most 25 results - top = 25 - # Sort by received time, newest first - order_by = 'receivedDateTime DESC' - request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' - - inbox_response = this.user_client.get(request_url) - return inbox_response.json() -# - -# -def send_mail(subject: str, body: str, recipient: str): - request_body = { - 'message': { - 'subject': subject, - 'body': { - 'contentType': 'text', - 'content': body - }, - 'toRecipients': [ - { - 'emailAddress': { - 'address': recipient + # + def get_user_token(self): + graph_scopes = self.settings['graphUserScopes'] + access_token = self.device_code_credential.get_token(graph_scopes) + return access_token.token + # + + # + def get_user(self): + endpoint = '/me' + # Only request specific properties + select = 'displayName,mail,userPrincipalName' + request_url = f'{endpoint}?$select={select}' + + user_response = self.user_client.get(request_url) + return user_response.json() + # + + # + def get_inbox(self): + endpoint = '/me/mailFolders/inbox/messages' + # Only request specific properties + select = 'from,isRead,receivedDateTime,subject' + # Get at most 25 results + top = 25 + # Sort by received time, newest first + order_by = 'receivedDateTime DESC' + request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' + + inbox_response = self.user_client.get(request_url) + return inbox_response.json() + # + + # + def send_mail(self, subject: str, body: str, recipient: str): + request_body = { + 'message': { + 'subject': subject, + 'body': { + 'contentType': 'text', + 'content': body + }, + 'toRecipients': [ + { + 'emailAddress': { + 'address': recipient + } } - } - ] + ] + } } - } - - request_url = '/me/sendmail' - - this.user_client.post(request_url, - data=json.dumps(request_body), - headers={'Content-Type': 'application/json'}) -# - -# -def ensure_graph_for_app_only_auth(): - if not hasattr(this, 'client_credential'): - client_id = this.settings['clientId'] - tenant_id = this.settings['tenantId'] - client_secret = this.settings['clientSecret'] - - this.client_credential = ClientSecretCredential(tenant_id, client_id, client_secret) - - if not hasattr(this, 'app_client'): - this.app_client = GraphClient(credential=this.client_credential, - scopes=['https://graph.microsoft.com/.default']) -# - -# -def get_users(): - ensure_graph_for_app_only_auth() - - endpoint = '/users' - # Only request specific properties - select = 'displayName,id,mail' - # Get at most 25 results - top = 25 - # Sort by display name - order_by = 'displayName' - request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' - - users_response = this.app_client.get(request_url) - return users_response.json() -# - -# -def make_graph_call(): - # INSERT YOUR CODE HERE - # Note: if using app_client, be sure to call - # ensure_graph_for_app_only_auth before using it - # ensure_graph_for_app_only_auth() - return -# + + request_url = '/me/sendmail' + + self.user_client.post(request_url, + data=json.dumps(request_body), + headers={'Content-Type': 'application/json'}) + # + + # + def ensure_graph_for_app_only_auth(self): + if not hasattr(self, 'client_credential'): + client_id = self.settings['clientId'] + tenant_id = self.settings['tenantId'] + client_secret = self.settings['clientSecret'] + + self.client_credential: ClientSecretCredential = ClientSecretCredential(tenant_id, client_id, client_secret) + + if not hasattr(self, 'app_client'): + self.app_client: GraphClient = GraphClient(credential=self.client_credential, + scopes=['https://graph.microsoft.com/.default']) + # + + # + def get_users(self): + self.ensure_graph_for_app_only_auth() + + endpoint = '/users' + # Only request specific properties + select = 'displayName,id,mail' + # Get at most 25 results + top = 25 + # Sort by display name + order_by = 'displayName' + request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' + + users_response = self.app_client.get(request_url) + return users_response.json() + # + + # + def make_graph_call(self): + # INSERT YOUR CODE HERE + # Note: if using app_client, be sure to call + # ensure_graph_for_app_only_auth before using it + # self.ensure_graph_for_app_only_auth() + return + # diff --git a/demo/graphtutorial/main.py b/demo/graphtutorial/main.py index ea15be4..0581fd6 100644 --- a/demo/graphtutorial/main.py +++ b/demo/graphtutorial/main.py @@ -3,7 +3,7 @@ # import configparser -import graph +from graph import Graph def main(): print('Python Graph Tutorial\n') @@ -13,9 +13,9 @@ def main(): config.read(['config.cfg', 'config.dev.cfg']) azure_settings = config['azure'] - initialize_graph(azure_settings) + graph: Graph = Graph(azure_settings) - greet_user() + greet_user(graph) choice = -1 @@ -36,26 +36,21 @@ def main(): if choice == 0: print('Goodbye...') elif choice == 1: - display_access_token() + display_access_token(graph) elif choice == 2: - list_inbox() + list_inbox(graph) elif choice == 3: - send_mail() + send_mail(graph) elif choice == 4: - list_users() + list_users(graph) elif choice == 5: - make_graph_call() + make_graph_call(graph) else: print('Invalid choice!\n') # -# -def initialize_graph(settings: configparser.SectionProxy): - graph.initialize_graph_for_user_auth(settings) -# - # -def greet_user(): +def greet_user(graph: Graph): user = graph.get_user() print('Hello,', user['displayName']) # For Work/school accounts, email is in mail property @@ -64,13 +59,13 @@ def greet_user(): # # -def display_access_token(): +def display_access_token(graph: Graph): token = graph.get_user_token() print('User token:', token, '\n') # # -def list_inbox(): +def list_inbox(graph: Graph): message_page = graph.get_inbox() # Output each message's details @@ -86,7 +81,7 @@ def list_inbox(): # # -def send_mail(): +def send_mail(graph: Graph): # Send mail to the signed-in user # Get the user for their email address user = graph.get_user() @@ -97,7 +92,7 @@ def send_mail(): # # -def list_users(): +def list_users(graph: Graph): users_page = graph.get_users() # Output each users's details @@ -112,7 +107,7 @@ def list_users(): # # -def make_graph_call(): +def make_graph_call(graph: Graph): graph.make_graph_call() # From 61c66ffee830dff666bb8b3ccb502b52c9152993 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 11:52:31 -0400 Subject: [PATCH 04/13] Refactor --- demo/graphtutorial/graph.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/demo/graphtutorial/graph.py b/demo/graphtutorial/graph.py index 58148ad..7c4bd89 100644 --- a/demo/graphtutorial/graph.py +++ b/demo/graphtutorial/graph.py @@ -4,13 +4,19 @@ # import json from configparser import SectionProxy +from types import NoneType from azure.identity import DeviceCodeCredential, ClientSecretCredential from msgraph.core import GraphClient class Graph: + settings: SectionProxy + device_code_credential: DeviceCodeCredential + user_client: GraphClient + client_credential: ClientSecretCredential + app_client: GraphClient def __init__(self, config: SectionProxy): - self.settings: SectionProxy = config + self.settings = config client_id = self.settings['clientId'] tenant_id = self.settings['authTenant'] graph_scopes = self.settings['graphUserScopes'].split(' ') @@ -85,11 +91,11 @@ def ensure_graph_for_app_only_auth(self): tenant_id = self.settings['tenantId'] client_secret = self.settings['clientSecret'] - self.client_credential: ClientSecretCredential = ClientSecretCredential(tenant_id, client_id, client_secret) + self.client_credential = ClientSecretCredential(tenant_id, client_id, client_secret) if not hasattr(self, 'app_client'): - self.app_client: GraphClient = GraphClient(credential=self.client_credential, - scopes=['https://graph.microsoft.com/.default']) + self.app_client = GraphClient(credential=self.client_credential, + scopes=['https://graph.microsoft.com/.default']) # # From 4b814061a895ca492049790189eb7a76c49ff968 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 11:56:58 -0400 Subject: [PATCH 05/13] Fix pylint errors --- demo/graphtutorial/graph.py | 2 +- demo/graphtutorial/pylintrc | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/demo/graphtutorial/graph.py b/demo/graphtutorial/graph.py index 7c4bd89..43a6223 100644 --- a/demo/graphtutorial/graph.py +++ b/demo/graphtutorial/graph.py @@ -4,7 +4,6 @@ # import json from configparser import SectionProxy -from types import NoneType from azure.identity import DeviceCodeCredential, ClientSecretCredential from msgraph.core import GraphClient @@ -116,6 +115,7 @@ def get_users(self): # # + # pylint: disable-next=no-self-use def make_graph_call(self): # INSERT YOUR CODE HERE # Note: if using app_client, be sure to call diff --git a/demo/graphtutorial/pylintrc b/demo/graphtutorial/pylintrc index 77936bd..b54b9d8 100644 --- a/demo/graphtutorial/pylintrc +++ b/demo/graphtutorial/pylintrc @@ -84,6 +84,7 @@ confidence= # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=C0114, + C0115, C0116 # Enable the message, report, category or checker with the given id(s). You can From fd12ce38a9e9167250e45756b8366ec1c472f3ea Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 11:59:20 -0400 Subject: [PATCH 06/13] Intentional error to test pylint --- demo/graphtutorial/graph.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/graphtutorial/graph.py b/demo/graphtutorial/graph.py index 43a6223..7385b44 100644 --- a/demo/graphtutorial/graph.py +++ b/demo/graphtutorial/graph.py @@ -110,7 +110,7 @@ def get_users(self): order_by = 'displayName' request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' - users_response = self.app_client.get(request_url) + users_response = self.app_client.gret(request_url) return users_response.json() # From efb78c02876ce608033692b37f71042c299bd233 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 12:03:15 -0400 Subject: [PATCH 07/13] Removing error --- demo/graphtutorial/graph.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/graphtutorial/graph.py b/demo/graphtutorial/graph.py index 7385b44..43a6223 100644 --- a/demo/graphtutorial/graph.py +++ b/demo/graphtutorial/graph.py @@ -110,7 +110,7 @@ def get_users(self): order_by = 'displayName' request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' - users_response = self.app_client.gret(request_url) + users_response = self.app_client.get(request_url) return users_response.json() # From 351e5b96d9ccd76d842dd9b41ea4667f71027745 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 12:37:07 -0400 Subject: [PATCH 08/13] Create auto-merge-dependabot.yml --- .github/workflows/auto-merge-dependabot.yml | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 .github/workflows/auto-merge-dependabot.yml diff --git a/.github/workflows/auto-merge-dependabot.yml b/.github/workflows/auto-merge-dependabot.yml new file mode 100644 index 0000000..6022314 --- /dev/null +++ b/.github/workflows/auto-merge-dependabot.yml @@ -0,0 +1,31 @@ +name: Auto-merge dependabot updates + +on: + pull_request: + branches: [ main ] + +permissions: + pull-requests: write + contents: write + +jobs: + + dependabot-merge: + + runs-on: ubuntu-latest + + if: ${{ github.actor == 'dependabot[bot]' }} + + steps: + - name: Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v1 + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + + - name: Enable auto-merge for Dependabot PRs + if: ${{steps.metadata.outputs.update-type != 'version-update:semver-major'}} + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} From 9a5c069c61516a9131b9ea95bd5ac3ca1558927a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 26 May 2022 16:39:06 +0000 Subject: [PATCH 09/13] Bump pyjwt from 2.3.0 to 2.4.0 in /demo/graphtutorial Bumps [pyjwt](https://github.com/jpadilla/pyjwt) from 2.3.0 to 2.4.0. - [Release notes](https://github.com/jpadilla/pyjwt/releases) - [Changelog](https://github.com/jpadilla/pyjwt/blob/master/CHANGELOG.rst) - [Commits](https://github.com/jpadilla/pyjwt/compare/2.3.0...2.4.0) --- updated-dependencies: - dependency-name: pyjwt dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- demo/graphtutorial/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/graphtutorial/requirements.txt b/demo/graphtutorial/requirements.txt index ca367ed..8f07a17 100644 --- a/demo/graphtutorial/requirements.txt +++ b/demo/graphtutorial/requirements.txt @@ -10,7 +10,7 @@ msal-extensions==1.0.0 msgraph-core==0.2.2 portalocker==2.4.0 pycparser==2.21 -PyJWT==2.3.0 +PyJWT==2.4.0 requests==2.27.1 six==1.16.0 typing_extensions==4.2.0 From 6b1fa1f7ba992cdbcc898f100e8a51ecc353d709 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 26 May 2022 16:40:24 +0000 Subject: [PATCH 10/13] Bump azure-core from 1.23.1 to 1.24.0 in /demo/graphtutorial Bumps [azure-core](https://github.com/Azure/azure-sdk-for-python) from 1.23.1 to 1.24.0. - [Release notes](https://github.com/Azure/azure-sdk-for-python/releases) - [Commits](https://github.com/Azure/azure-sdk-for-python/compare/azure-core_1.23.1...azure-core_1.24.0) --- updated-dependencies: - dependency-name: azure-core dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- demo/graphtutorial/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/graphtutorial/requirements.txt b/demo/graphtutorial/requirements.txt index 8f07a17..8b315f1 100644 --- a/demo/graphtutorial/requirements.txt +++ b/demo/graphtutorial/requirements.txt @@ -1,4 +1,4 @@ -azure-core==1.23.1 +azure-core==1.24.0 azure-identity==1.10.0 certifi==2021.10.8 cffi==1.15.0 From 222c912fa3c3e83e29a7c265c65de8552101b53f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 26 May 2022 16:40:38 +0000 Subject: [PATCH 11/13] Bump cryptography from 37.0.1 to 37.0.2 in /demo/graphtutorial Bumps [cryptography](https://github.com/pyca/cryptography) from 37.0.1 to 37.0.2. - [Release notes](https://github.com/pyca/cryptography/releases) - [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pyca/cryptography/compare/37.0.1...37.0.2) --- updated-dependencies: - dependency-name: cryptography dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- demo/graphtutorial/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/graphtutorial/requirements.txt b/demo/graphtutorial/requirements.txt index 8f07a17..cfd8c6d 100644 --- a/demo/graphtutorial/requirements.txt +++ b/demo/graphtutorial/requirements.txt @@ -3,7 +3,7 @@ azure-identity==1.10.0 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.12 -cryptography==37.0.1 +cryptography==37.0.2 idna==3.3 msal==1.17.0 msal-extensions==1.0.0 From e3b6dc3c3659ea4e96271097083ce0d83dfe17e3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 26 May 2022 16:41:58 +0000 Subject: [PATCH 12/13] Bump certifi from 2021.10.8 to 2022.5.18.1 in /demo/graphtutorial Bumps [certifi](https://github.com/certifi/python-certifi) from 2021.10.8 to 2022.5.18.1. - [Release notes](https://github.com/certifi/python-certifi/releases) - [Commits](https://github.com/certifi/python-certifi/compare/2021.10.08...2022.05.18.1) --- updated-dependencies: - dependency-name: certifi dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- demo/graphtutorial/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demo/graphtutorial/requirements.txt b/demo/graphtutorial/requirements.txt index ef98c10..554af59 100644 --- a/demo/graphtutorial/requirements.txt +++ b/demo/graphtutorial/requirements.txt @@ -1,6 +1,6 @@ azure-core==1.24.0 azure-identity==1.10.0 -certifi==2021.10.8 +certifi==2022.5.18.1 cffi==1.15.0 charset-normalizer==2.0.12 cryptography==37.0.2 From 1eddc7f141b0ba68e8e3ff9454b67d758b196f10 Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Thu, 26 May 2022 12:44:49 -0400 Subject: [PATCH 13/13] Update README.md --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 59c1a24..6ad0727 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,7 @@ -# msgraph-training-python -Completed project for Build Python apps with Microsoft Graph - - # Build Python apps with Microsoft Graph - Completed project +[![Pylint](https://github.com/microsoftgraph/msgraph-training-python/actions/workflows/pylint.yml/badge.svg)](https://github.com/microsoftgraph/msgraph-training-python/actions/workflows/pylint.yml) + This sample will introduce you to working with the Microsoft Graph SDK to access data in Microsoft 365 from Python applications. This code is the result of completing the [Python Microsoft Graph tutorial](https://docs.microsoft.com/graph/tutorials/python). ## Running the sample