AWS |
AWS Startups Blog |
Shining a spotlight on startup solutions with speedy market entry |
https://aws.amazon.com/blogs/startups/shining-a-spotlight-on-startup-solutions-with-speedy-market-entry/
|
Shining a spotlight on startup solutions with speedy market entryWe showcase three winners in the GTM Innovator category of the AWS Software Startups Awards These super charged startups have won customers and secured partnerships through leveraging AWS programs They ve also adapted AWS technology and tools to suit their specific needs and created solutions and platforms to transform how they interact with consumers and enterprises |
2022-12-15 19:30:05 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
AWS Verified Access で VPN-less な世界を体験してみた |
https://qiita.com/hayao_k/items/5f3b8a88a0ea75828f95
|
adventcalendar |
2022-12-16 04:14:24 |
海外TECH |
MakeUseOf |
The 11 Best iOS Features That Android Still Doesn't Have |
https://www.makeuseof.com/best-ios-features-missing-from-android/
|
android |
2022-12-15 19:45:16 |
海外TECH |
MakeUseOf |
7 Photography Trends We Should Leave Behind in 2022 |
https://www.makeuseof.com/photography-trends-to-leave-behind-in-2022/
|
techniques |
2022-12-15 19:30:15 |
海外TECH |
MakeUseOf |
How to Use Instagram's Notes Feature to Post a Status |
https://www.makeuseof.com/how-to-use-instagram-notes-post-status/
|
notes |
2022-12-15 19:27:25 |
海外TECH |
DEV Community |
What are classes in python? |
https://dev.to/ezinne_anne/what-are-classes-in-python-451c
|
What are classes in python Python is an object oriented programming language In Python everything is an object All this time that you have been writing code you have used objects Either when you used built in functions or the variables you created An object is any data you can assign to a variable or pass as an argument to a function or method A method is a function passed into an object Check my previous article if you are yet to learn about functions in Python In this article you will learn Creating a ClassThe init methodCalling the class instanceSetting A Default ValueInheritanceInheriting from the parentImporting classesConclusion Creating a Class A class is an outline or layout for creating objects You can create many objects from a class The object you create from a class is called an instance You could also create methods A class is like a recipe while the food prepared is the object A class is a layout for creating objects so it does not hold any actual data You cannot pass an argument to a class but you can to an object To create a class you begin with the word class then the class name and a colon This is the syntax class ClassName Creating a simple syntax Note In Python classes are capitalized in camel case Eg CamelCaseLetterFor example if you wanted to create a class that records information about your students you could do so class Student Creating a class that records student details name courses complete certificates After creating the class create an object which is called an instance of the class I will be addressing it as an instance from now on to avoid any confusion This is the syntax instance name ClassName you do not need to capitalize the instance name or use Camel case You create the instance and assign it to the class name In the student record example create the instance class Student Creating a class that records student details name courses complete certificates student details Student You can change the values for the class attributes when you want to access them student details name Ezinne Anne Emilia Now print all the values for the attributes after modifying them class Student Creating a class that records student details name courses complete certificates student details Student student details name Ezinne Anne Emilia modifying the value of the name attribute student details courses complete modifying the value of the courses complete attribute student details certificates modifying the value of the certificates attribute print f Student s Name student details name n Courses Completed student details courses complete n Certificates Received student details certificates printing the values to the consoleOutputStudent s Name Ezinne Anne Emilia Courses Completed Certificates Received In the past example you created attributes called name courses complete and certificates But to access these attributes you had to change the values directly in the instance But wouldn t it be better if you used those attributes as parameters and passed the values as arguments in the instance instead Of course it would be You can do that with a special method called the init method The init method The init method is a constructor function This function initializes a new instance of the class Python requires the self parameter when initializing a new instance So when you create an instance Python will automatically pass the self parameter You should surround the init method with double underscores So the Python interpreter does not misinterpret it as a different method This is the syntax def init self attribute attribute self attribute attribute self attribute attributeNow use the init method in the Student class exampleclass Student Creating a class that records student details def init self name courses complete certificates Initializing the attributes for the class instance self name name self courses complete courses complete self certificates certificatesstudent details Student Ezinne Anne Emilia there s no argument for the self parameterprint f Student s Name student details name n Courses Completed student details courses complete n Certificates Received student details certificates OutputStudent s Name Ezinne Anne Emilia Courses Completed Certificates Received This makes the code cleaner right Now if you noticed when I filled in the arguments for the class Student I didn t add an argument for the self parameter This is due to the Python interpreter passing the self parameter to the student details instance Now you can add more methods to the code In the code example you can add features that indicate when a student has started a course And when a student has finished a course class Student Creating a class that records student details def init self name courses complete certificates Initializing the attributes for the class instance self name name self courses complete courses complete self certificates certificates def start self Creating a method that indicates when a student starts a course print f This student self name has started a course def complete self Creating a method that indicates when a student completes a course print f This student self name has completed a course student details Student Ezinne Anne Emilia print f Student s Name student details name n Courses Completed student details courses complete n Certificates Received student details certificates When creating the methods start and complete you added the self parameter to them This makes the attributes initialized in the constructor function available in the methods too But you can add more parameters to the method after you add the self parameter def start self prev record Creating a method that indicates when a student starts a course prev record print f This student self name has started a course n Previous record prev record Calling the class instance To call the methods that you created you use the name of the instance and the name of the method This is the syntax instance name method name To call the methods in the Student class class Student Creating a class that records student details def init self name courses complete certificates self name name self courses complete courses complete self certificates certificates def start self prev record Creating a method that indicates when a student starts a course prev record print f This student self name has started a course n Previous record prev record def complete self Creating a method that indicates when a student completes a course print f This student self name has completed a course student details Student Ezinne Anne Emilia print f Student s Name student details name n Courses Completed student details courses complete n Certificates Received student details certificates student details start student details complete OutputStudent s Name Ezinne Anne Emilia Courses Completed Certificates Received This student Ezinne Anne Emilia has started a course Previous record This student Ezinne Anne Emilia has completed a courseSetting A Default Value You could set a default value for an attribute without adding it as a parameter For example if you wanted to record courses completedYou could create a default value in the constructor function class Student Creating a class that records student details def init self name courses complete certificates self name name self courses complete courses complete self certificates certificates self previous record def previous courses self creating a method that records previous courses done print f Previous record self previous record student details previous courses You can modify previous record directly like this student details previous record student details previous courses Instead of modifying it directly you could also change the attribute through a method instead class Student Creating a class that records student details def init self name courses complete certificates self name name self courses complete courses complete self certificates certificates self previous record def update previous courses self updated record Creating a method to update previous courses done if updated record self previous record self previous record updated record else print recorded student details update previous courses student details previous courses Inheritance This is when the child class inherits the properties of the parent class If you created a class called User and you wanted to create another class called UserProfile you could inherit the properties of the parent class instead of writing the code from scratch This is the syntax class Parent Creating a parent class class Child Parent Creating a child class def init self param param Initializing super init parent param parent param Inheriting from the parent In the child class you use the super method to initialize the attributes of the parent class In this example the UserProfile class will inherit the attributes of the User class class User creating a class for a user login attempts def init self device ip address fixing the attributes for the user self device device attribute for the user s device self ip address ip address attribute for the user s ip address self login attempts attribute for the user s login attempts def register self creating a method that describes the user s registration print f This user has been registered successfully def location self creating a method that describes the user s location print f This device is located at the Northern hemisphere def failed logins self creating a method that records login attempts print f This user has self login attempts login attempts class UserProfile User Creating a child class UserProfile that will inherit some of the attributes of the parent class User def init self device ip address Initializing the attributes of the parent class super init device ip address user profile User HuaweiX assigning the argumentsprint f This user is using a mobile device user profile device n Address user profile ip address user profile failed logins You could add new attributes and methods to a child s class In this example you could add the name age and username of the user and a method to describe the user profile class User creating a class for a user login attempts def init self device ip address fixing the attributes for the user self device device attribute for the user s device self ip address ip address attribute for the user s ip address self login attempts attribute for the user s login attempts def register self creating a method that describes the user s registration print f This user has been registered successfully def location self creating a method that describes the user s location print f This self device is located at the Northern hemisphere def failed logins self creating a method that records login attempts print f This user has self login attempts login attempts class UserProfile User Creating a child class UserProfile that will inherit some of the attributes of the parent class User def init self device ip address name age username adding new attributes to the child class initializing the attribute of the parent in the child class super init device ip address self name name self age age self username username def describe user self describing a user print f User details n Name self name n Age self age n Username self username user profile UserProfile Gionee Ezinne eziny assigning the argumentsuser profile location calling the method of the parent class on the child classuser profile describe user OutputThis Gionee is located at the Northern hemisphereUser details Name Ezinne Age Username eziny Importing classes In python you can import classes in your code You can import a single class Syntax from file name import ClassNameCommand from user import UserYou can import multiple classes from a file into the current code you are writing Syntax from file name import ClassName ClassNameinstance name ClassName attribute attribute Command from user import User UserProfileuser User device address You can also import the whole file by specifying the file name Syntax import file nameCommand import userTo import all classes from a file into your present code Syntax from file name import Command from user import To import a file and give it another name or aliasSyntax from file name import ClassName as CNCommand from user import UserProfile as UP Conclusion By the end of this article you will have learned about OOP in Python how to create a class the init method and methods creating an instance and how to import classes You could try to repeat the initial exercises using the user login class this time around |
2022-12-15 19:20:05 |
Apple |
AppleInsider - Frontpage News |
How to use SSH for secure connections in macOS |
https://appleinsider.com/inside/macos/tips/how-to-use-ssh-for-secure-connections-in-macos?utm_medium=rss
|
How to use SSH for secure connections in macOSThe Secure Shell ーSSH ーallows you to send secure encrypted communications between computers that is nearly impossible to crack Here s how to use it in macOS Before personal computers people used time sharing terminals in computer labs which were attached to mainframe computers Each user sat at a dumb terminal which was merely a display and keyboard connected to the mainframe computer Later as mini computers began to arrive terminals were connected via a network Originally to access another computer on a network remotely a program called Telnet was used Telnet was one of the earliest internet applications and was widely used in university and research settings Security wasn t considered an issue at the time since most people still didn t use the internet and mass online fraud wasn t a problem Read more |
2022-12-15 19:57:04 |
Apple |
AppleInsider - Frontpage News |
Belkin has a Continuity Camera MagSafe Mount for monitors now |
https://appleinsider.com/articles/22/12/15/belkin-has-a-continuity-camera-magsafe-mount-for-monitors-now?utm_medium=rss
|
Belkin has a Continuity Camera MagSafe Mount for monitors nowContinuity camera uses the iPhone camera as a Mac webcam and Belkin is now offering a new MagSafe mount for monitors The Belkin iPhone Mount fits on desktop monitorsBelkin offers a MagSafe iPhone mount for Continuity Camera already but it is built for attaching to the thin lid of a MacBook The accessory maker has a new model available for desktops like the Studio Display Read more |
2022-12-15 19:48:40 |
Apple |
AppleInsider - Frontpage News |
Apple now testing Rapid Security Response updates in macOS Ventura 13.2 beta |
https://appleinsider.com/articles/22/12/15/apple-now-testing-rapid-security-response-updates-in-macos-ventura-132-beta?utm_medium=rss
|
Apple now testing Rapid Security Response updates in macOS Ventura betaA day after the first developer beta of macOS Ventura was released Apple has issued a Rapid Security Response for the operating system Beta testers get a Rapid Security ResponseAdded in iOS iPadOS and macOS Ventura Apple uses Rapid Security Response to issue urgent security patches to users quickly It s separate from the regular system update channel Read more |
2022-12-15 19:33:17 |
海外TECH |
Engadget |
'Mythic Quest' is getting an Apple TV+ spinoff series |
https://www.engadget.com/mythic-quest-spinoff-apple-tv-plus-meme-mortals-192207925.html?src=rss
|
x Mythic Quest x is getting an Apple TV spinoff seriesApple TV has announced a Mythic Quest spinoff show The streaming service hasn t revealed too many details about Mere Mortals just yet However it did say the so called extension series will delve deeper into the lives of the employees players and fans who are impacted by Mythic Quest the fictional game at the heart of the eponymous sitcom Mere Mortals will take inspiration from Mythic Quest departure episodes such as the standalone Everlight Backstory which is set in and Quarantine which showed how the characters were dealing with COVID lockdowns Mythic Quest writers Ashly Burch John Howell Harris and Katie McElhenney created the eight episode spinoff Burch who also stars as Aloy in Sony s Horizon games plays Rachel in the original show Mythic Quest creators Megan Ganz Rob McElhenney and Charlie Day are involved as executive producers as well Apple TV didn t say when Mere Mortals will debut Season of Mythic Quest premiered on the streaming service last month |
2022-12-15 19:22:07 |
ニュース |
BBC News - Home |
Eight children among 39 rescued from migrant boat |
https://www.bbc.co.uk/news/uk-63982143?at_medium=RSS&at_campaign=KARANGA
|
boata |
2022-12-15 19:53:17 |
ニュース |
BBC News - Home |
Manchester United cut capacity for Burnley match because of ambulance strike |
https://www.bbc.co.uk/sport/football/63993088?at_medium=RSS&at_campaign=KARANGA
|
Manchester United cut capacity for Burnley match because of ambulance strikeManchester United reduce Old Trafford capacity by for next Wednesday s Carabao Cup match with Burnley because of ambulance strike on the same day |
2022-12-15 19:16:39 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
2022年の漢字は「戦」、歴代の“今年の漢字”とともに日本経済超ざっくり学び直し - News&Analysis |
https://diamond.jp/articles/-/314451
|
newsampampanalysis |
2022-12-16 04:50:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
2022年の漢字は「戦」、“今年の漢字”で日本経済超ざっくり学び直し!23年はどうなる? - News&Analysis |
https://diamond.jp/articles/-/314694
|
newsampampanalysis |
2022-12-16 04:49:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
ハーバード大教授が指摘、グローバル化を決断できた日本企業の「CEOの共通点」 - ハーバードの知性に学ぶ「日本論」 佐藤智恵 |
https://diamond.jp/articles/-/314270
|
佐藤智恵 |
2022-12-16 04:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「私が責任を取る」という上司が実はダメ上司である理由 - 「40代で戦力外」にならない!新・仕事の鉄則 |
https://diamond.jp/articles/-/314386
|
至上主義 |
2022-12-16 04:40:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
インフレなのに金融緩和継続?日銀・黒田総裁が踏み切った「危険な賭け」 - 政策・マーケットラボ |
https://diamond.jp/articles/-/314570
|
インフレなのに金融緩和継続日銀・黒田総裁が踏み切った「危険な賭け」政策・マーケットラボ日銀は、年以内にの物価安定目標を達成するという短期決戦を想定したが、その目論見は見事に外れ、いつ終わるともしれない資産の膨張が始まってしまった。 |
2022-12-16 04:35:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
元世界2位のトップセールスが「月次」でなく「週次」の手帳にこだわる理由 - 和田裕美のステップアップ仕事論 |
https://diamond.jp/articles/-/314376
|
和田裕美 |
2022-12-16 04:30:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
Jリーグ「引き分け廃止・PK決着」で次のW杯は日本勝利!コンサルのガチ提言 - 今週もナナメに考えた 鈴木貴博 |
https://diamond.jp/articles/-/314678
|
実は私は |
2022-12-16 04:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
中国ゼロコロナ緩和の実態は「突然すぎる全面撤退」、国民に広がる不安 - ふるまいよしこ「マスコミでは読めない中国事情」 |
https://diamond.jp/articles/-/314639
|
|
2022-12-16 04:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
米国民はインフレに激怒も「自作自演」状態の皮肉…データで見る物価高の真相 - DOL特別レポート |
https://diamond.jp/articles/-/314069
|
|
2022-12-16 04:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
ゼロコロナ緩和で中国のビジネス意欲復活、世界中に商談チーム続々訪問 - 莫邦富の中国ビジネスおどろき新発見 |
https://diamond.jp/articles/-/314677
|
中国ビジネス |
2022-12-16 04:10:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「Twitter離れ」ならマストドン?タンブラー?何を選んでも相互接続するかも - ニュース3面鏡 |
https://diamond.jp/articles/-/314107
|
「Twitter離れ」ならマストドンタンブラー何を選んでも相互接続するかもニュース面鏡イーロン・マスク氏の買収で、Twitterが揺れている。 |
2022-12-16 04:05:00 |
ビジネス |
東洋経済オンライン |
京都鉄道博物館、車両展示だけでない「重要使命」 「大地震」で鉄道ストップ、帰れなくなったら? | 経営 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/639828?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
京都鉄道博物館 |
2022-12-16 04:30:00 |
GCP |
Cloud Blog |
How to develop and test your Cloud Functions locally |
https://cloud.google.com/blog/topics/developers-practitioners/how-to-develop-and-test-your-cloud-functions-locally/
|
How to develop and test your Cloud Functions locallyDeveloping code for serverless platforms requires a different approach to your development flow Since the platform provides and maintains the entire stack from compute infrastructure up to the function handler your code runs in a fully managed and abstracted environment This can make it time consuming and inefficient to debug your code by deploying and invoking a Function in the cloud Fortunately Cloud Functions offers an alternative that lets you implement and debug your code much faster In this blog post you ll learn how to do the following Run a Cloud Function locallyInvoke a Cloud Function with an Eventarc event locallyUse the same permissions as if it were deployed in the CloudFetch secrets stored remotely from Secret ManagerSet Breakpoints in Visual Studio Code within a local Cloud FunctionCloud Functions builds upon the open source Functions FrameworkGoogle Cloud strongly drives and aligns on open standards and open source Cloud Functions are no exception In fact Google has a fully open sourced runtime environment responsible for wrapping a function code within a persistent HTTP application known as the Functions Framework It enables developers to run the same runtime environment as Cloud Functions on their machines or anywhere else As a developer you no longer need to make assumptions about how the serverless environment will behave or how to emulate the production experience As shown above a nd gen Cloud Function actually represents a container hosted on Google s Serverless container infrastructure Google fully provides the container s operation system the necessary language runtime and the Functions Framework All these layers are packed together with your function code and its dependencies using Cloud Native Buildpacks during the deployment process A real world exampleHere is a typical example of a TypeScript application that processes thousands of images daily This application derives insights from images and stores the resulting object labels The following diagram illustrates this scenario as an event driven microservice For each newly uploaded image to a Cloud Storage bucket Eventarc invokes a nd gen Cloud Functionand passes along the image location including other event metadata The TypeScript application code needs to access a secret stored in Secret Manager uses the Vision API to extract object labels and indexes the image to a Cloud Firestore document database The following code snippet shows the function code The full example is available in this GitHub repository code block StructValue u code u cloudEvent index async cloudevent CloudEvent lt StorageObjectData gt gt r n console log nProcessing for cloudevent subject n r n r n if cloudevent data r n throw CloudEvent does not contain data r n r n r n const filePath cloudevent data bucket cloudevent data name r n r n Get labes for Image via the Vision API r n const result await imageAnnotatorClient labelDetection gs filePath r n const labelValues result labelAnnotations flatMap o gt o description r n r n hash file name with secret r n const hashedFilePath createHmac sha secret r n update filePath r n digest hex r n r n Store with filePath as key r n await firestore r n doc cloudevent data bucket hashedFilePath r n set r n r n name cloudevent data name r n labels labelValues r n updated cloudevent time r n r n r n r n console log Successfully stored cloudevent data name to Firestore r n u language u u caption lt wagtail wagtailcore rich text RichText object at xeaacd gt This Function code uses multiple dependencies from the Google Cloud ecosystem Eventarc to trigger an invocation Secret Manager to provide a secret for filename encryptionCloud Vision API to detect and fetch labels for the uploaded imageCloud Firestore for storing the resultThe README file in the repository contains all necessary steps to deploy this example application in your Google Cloud project In the following section you will learn how to set up your local development environment to execute this TypeScript function outside of Cloud Functions This setup allows you to iterate faster on your code by testing locally before deploying How to run a Cloud Function locally The Functions Framework can be installed and run on any platform that supports the language including your local machine or remote development servers As shown in this example function s directory you can install the Functions Framework library for TypeScript with the following CLI command If your language of choice is Python Go Java C Ruby or PHP you can checkout the documentation about how to install the Functions Framework for your preferred language code block StructValue u code u npm install save google cloud functions framework u language u u caption lt wagtail wagtailcore rich text RichText object at xeaadc gt Since the application is using TypeScript you need to compile the source code and reference the output folder as the source for the Functions Framework The following code snippet from the package json allows for a convenient hot reload and uses tsc with the w watch flag to watch for changes to recompile It also uses nodemon to watch for newly compiled files to automatically restart the local Functions Framework code block StructValue u code u scripts r n r n compile tsc r n debug node inspect node modules bin functions framework source build src target index r n watch concurrently npm run compile watch nodemon watch build exec npm run debug r n r n u language u u caption lt wagtail wagtailcore rich text RichText object at xeaadced gt After installing all application dependencies with npm install you can use the command npm run watch to generate a local endpoint http localhost Let s investigate how to use this local endpoint of your event triggered Cloud Function How to invoke a Cloud Function with an Eventarc event locallyThe function code expects to be invoked by Eventarc Eventarc uses the open standards of CloudEvents specifications for event structure The direct integration with Cloud Functions uses a HTTP protocol binding in which a HTTP request body contains event specific headers like type time source subject and specification version and a body with event data To invoke the Cloud Functions code locally with the expected HTTP request structure and payload you can use a simple curl command The following curl command implements the HTTP protocol binding for an google cloud storage object v finalized event of an uploaded image file CF debugging architecture png to the bucket called image bucket and invoking your Cloud Function listening on localhost port code block StructValue u code u curl localhost v r n X POST r n H Content Type application json r n H ce id r n H ce specversion r n H ce time T Z r n H ce type google cloud storage object v finalized r n H ce source storage googleapis com projects buckets image bucket r n H ce subject objects CF debugging architecture png r n d r n bucket image bucket r n contentType text plain r n kind storage object r n mdHash r n metageneration r n name CF debugging architecture png r n size r n storageClass MULTI REGIONAL r n timeCreated T Z r n timeStorageClassUpdated T Z r n updated T Z r n u language u u caption lt wagtail wagtailcore rich text RichText object at xeaecd gt Alternatively CloudEvents provides a CLI tool called CloudEvents Conformance for testing CloudEvents receivers It helps format the HTTP request by using a YAML file to define the expected Eventarc event of an uploaded image to a Cloud Storage Bucket You can find an example of such a yaml in the GitHub repository The example application assumes that the file CF debugging architecture png actually exists and is stored in image bucket bucket If the file does not exist the local execution will exit with an error However since this example Cloud Function relies on external dependencies like the Cloud Storage Bucket or the Vision API the invocation throws an UNAUTHENTICATED error immediately You ll see how to fix this in the next section To recap a simple curl command can be used to send an Eventarc event for an uploaded image using the HTTP protocol binding to invoke your code locally The HTTP body structure for other Eventarc events is available on the CloudEvents GitHub repository Next you ll see how to authenticate the local Cloud Function How to use the same permissions as if it were deployed in the CloudThe example Cloud Function uses the Node js client libraries to interact with Google Cloud services like the Vision API or Firestore Authentication for the client libraries happens automatically when deployed on Google Cloud However when you re working locally you ll need to configure authentication Google Cloud client libraries handle authentication automatically because they support Application Default Credentials ADC ADC automatically finds credentials based on the application environment and uses those credentials to authenticate to Google Cloud APIs When you deploy a Cloud Function Google Cloud provides Service Account credentials via the metadata server Also gcloud allows you to set ADC locally via gcloud auth application default login This command acquires your user credentials to use for ADC The impersonate service account flag further allows impersonating a Service Account and uses its identity for authentication against Google Cloud APIs For impersonating a Service Account your user account needs to have the Service Account Token Creator roles iam serviceAccountTokenCreator role for it The following command is setting ADCs for a specific Service Account locally code block StructValue u code u gcloud auth application default login r n impersonate service account YOUR SERVICE ACCOUNT EMAIL u language u u caption lt wagtail wagtailcore rich text RichText object at xeae gt For this example application you can use the same service account that is used by the Cloud Function i e the Function s identity when deployed on Google Cloud If you are not sure which service account is associated with your provisioned Cloud Function you can use the following command to retrieve its services account email code block StructValue u code u gcloud functions describe YOUR CLOUD FUNCTION NAME r n format value serviceConfig serviceAccountEmail u language u u caption lt wagtail wagtailcore rich text RichText object at xeadcd gt Using the same service account allows you to execute the code locally with the same permissions as the deployed Function Therefore you can properly test changes to the service account permissions during local execution After executing this command and restarting the local dev server with npm run watch the function code authenticates against the Vision API and Firestore Now the code can run and use Google Cloud services as if deployed on Cloud Functions directly without any code changes This makes local development very convenient When a Cloud Function is executed in the cloud any configured secrets from Secret Manager are included into the Function s container In the next section you ll see how you can reference those secrets in your local development environment How to fetch secrets stored remotely from Secret ManagerThe Cloud Function service allows customers to use Secret Manager to securely store API keys passwords and other sensitive information and pass those secrets as environment variables or mount them as a volume However in a local execution environment this automatic mechanism does not exist You will need to connect to the Secret Manager in a different way In this section you can see how the example application uses such a secret and accesses it via the environment variable SECRET API KEY For a local development environment a couple of options are available to use secrets You can use the Secret Manager client library to directly request the secret during runtime You can use the gcloud command gcloud secrets versions access to fetch a secret during runtime and inject it as an environment variable securely and in an automated way The package json illustrates this code block StructValue u code u scripts r n r n compile tsc r n debug export SECRET API KEY gcloud secrets versions access secret apikey impersonate service account YOUR SERVICE ACCOUNT amp amp node inspect node modules bin functions framework source build src target index r n watch concurrently npm run compile watch nodemon watch build exec npm run debug r n r n u language u u caption lt wagtail wagtailcore rich text RichText object at xeabcf gt When executing npm run watch the API key secret from Secret Manager is set as the SECRET API KEY environment variable only for this node process The impersonate service account flag allows for realistic secret permission handling in a local development environment at this point as well How to set Breakpoints in Visual Studio Code within a local Cloud FunctionDebugging is a core feature of the IDE Visual Studio Code and is also very useful when developing a Cloud Function The IDE has built in debugging support for the Node js runtime and can debug JavaScript TypeScript and many other languages The npm debug script in the package json contains the inspect flag when executing the Functions Framework code block StructValue u code u scripts r n r n debug export SECRET API KEY gcloud secrets versions access secret apikey impersonate service account YOUR SERVICE ACCOUNT amp amp node inspect node modules bin functions framework source build src target index r n r n u language u u caption lt wagtail wagtailcore rich text RichText object at xeabcfc gt This flag allows Visual Studio Code to attach its JavaScript debugger which supports TS source maps Source maps make it possible to single step through your code or set breakpoints in your uncompiled TypeScript files Using these built in Visual Studio Code debugging features provides you with a better debugging experience during local development After configuring Visual Studio Code to use the debugger s auto attachment functionality you can set breakpoints in the editor margin and then run npm run watch to activate the debugger mode When you invoke the local endpoint using either curl or the CloudEvents Conformance tool the function code will pause execution at the specified breakpoints This allows you to investigate the current variable assignments investigate the call stack and much more The screenshot above demonstrates how you can debug the processed labels and inspect the labelsValues variable during local execution In combination with hot reloading and access to remote dependencies debugging within Visual Studio Code speeds up the development cycle as it allows for testing and inspecting code changes in just seconds Wrapping upIn this article you saw how to develop and debug a TypeScript Cloud Function locally that contains external dependencies and is triggered by Eventarc events You learned how to set up hot reloading in combination with the Functions Framework to speed up debugging and testing changes in just a few seconds Additionally you saw how to use local and impersonated Application Default Credentials to execute the local function code with the same permissions as if deployed on Cloud Functions Lastly having the ability to retrieve secrets from the Secret Manager or using breakpoints in Visual Studio Code during debugging greatly support local development since you do not have to make any modifications to your code The open cloud approach of Google Cloud enables a familiar and productive development environment even when programming serverless applications Just stay local and develop and debug fast with Google Cloud Serverless Want to learn more Check out the resources below to dive in Local Development Cloud Functions DocumentationEventarc triggers Cloud Functions Documentation Cloud Run vs Cloud Functions for serverless Google Cloud Blog How Application Default Credentials works Authentication Google CloudTesting with the Pub Sub emulator Cloud Functions DocumentationRelated ArticleCloud Functions nd gen is GA delivering more events compute and controlWith Cloud Functions nd gen developers can write more powerful functions that integrate with more services and satisfy enterprise requ Read ArticleRelated ArticleCloud Functions vs Cloud Run when to use one over the otherWhen building on top of a serverless platform like Cloud Run or Cloud Functions here s a framework for deciding which to choose for a gi Read Article |
2022-12-15 20:00:00 |
コメント
コメントを投稿