投稿時間:2022-12-07 16:29:40 RSSフィード2022-12-07 16:00 分まとめ(33件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 「MY G-SHOCK」にパーツ追加、アルファベットのバックライトやボタンも https://www.itmedia.co.jp/business/articles/2212/07/news127.html gshock 2022-12-07 15:36:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] スーパーのおはぎに行列 なぜ? 宮城の秋保温泉で「1日2万4000個」 https://www.itmedia.co.jp/business/articles/2212/07/news138.html itmedia 2022-12-07 15:25:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 中途採用している企業の6割が、フリーターは「採用対象」 https://www.itmedia.co.jp/business/articles/2212/07/news117.html itmedia 2022-12-07 15:15:00
IT ITmedia 総合記事一覧 [ITmedia PC USER] CORSAIR、曲率変更機能を備えた45型有機ELゲーミングディスプレイ「45WQHD240」のカウントダウンページをオープン https://www.itmedia.co.jp/pcuser/articles/2212/07/news135.html corsair 2022-12-07 15:12:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 男性が結婚相手に求めること 3位「思いやり・気遣い」、2位「趣味への理解」、1位は? https://www.itmedia.co.jp/business/articles/2212/07/news134.html itmedia 2022-12-07 15:08:00
js JavaScriptタグが付けられた新着投稿 - Qiita ブラウザのオブジェクト https://qiita.com/masatom86650860/items/c054d69b05a88964ad8c consolelog 2022-12-07 15:16:12
Docker dockerタグが付けられた新着投稿 - Qiita Docker + gorm + gin で入れ子構造のAPIを作る https://qiita.com/yuramaru/items/75aabe89689d959ca031 docker 2022-12-07 15:53:13
golang Goタグが付けられた新着投稿 - Qiita Docker + gorm + gin で入れ子構造のAPIを作る https://qiita.com/yuramaru/items/75aabe89689d959ca031 docker 2022-12-07 15:53:13
Git Gitタグが付けられた新着投稿 - Qiita 【Github】SourceTreeからGithubにプッシュができないときの対処法 https://qiita.com/iwatsukayura/items/1ec8b5731e9b2e8c04c2 github 2022-12-07 15:54:30
技術ブログ Developers.IO 【レポート】The evolution of chaos engineering at Netflix #NFX303 #reinvent https://dev.classmethod.jp/articles/reinvent2022-nfx303-chaos-engineering-at-netflix/ engine 2022-12-07 06:48:02
技術ブログ Developers.IO [レポート] SPT101 AWSでどうやってF1TVのファンのエンゲージメントを向上させるか / How AWS helps F1TV increase fan engagement #reinvent https://dev.classmethod.jp/articles/reinvent2022-spt101/ レポートSPTAWSでどうやってFTVのファンのエンゲージメントを向上させるかHowAWShelpsFTVincreasefanengagementreinventMoi営業事務のサンニです。 2022-12-07 06:23:52
技術ブログ Developers.IO 【Update】การสร้าง Microsoft SQL Server 2019 Standard ใน Windows Server 2019 บน EC2 https://dev.classmethod.jp/articles/building-microsoft-sql-server-2019-standard-in-windows-server-2019-v2/ 【Update】การสร้างMicrosoft SQL Server Standard ในWindows Server บนECสวัสดีครับPOP จากบริษัทClassmethod Thailand ครับครั้งนี้ผมจะมาแนะนำการสร้างMicrosoft SQL Server Sta 2022-12-07 06:08:36
海外TECH DEV Community How to reverse an array in JavaScript https://dev.to/devmaradona/how-to-reverse-an-array-in-javascript-248j How to reverse an array in JavaScriptIn this article we will learn how to reverse an array in JavaScript There s more than one way to do this Using reverse method Built In Using for loopThere are two ways the first is easy because there s a built in function in JavaScript that does this and the second is to create that function with ourselves It is better for you in the production stage to use what is in the language but in the learning stage it is better to understand what is happening behind the scenes Our ProblemNow what is our problem The problem is that there s an array and we want to reverse it Imagine that there is a array like that And we want to reverse it to be like this As we said earlier we can solve the problem in two ways Using reverse method Built In Using for loop Using reverse method Built In We can use reverse method to solve our problem Example Arraylet myArray Reverse the arraylet reversedArr myArray reverse Result console log reversedArr Output This is the first solution and I do not recommend it at the learning stage because it does not benefit you much Using for loopNow before writing the code we must understand how we will solve this problem by for loop First iteration using for iterate over every element in the array right Well here it means that we can start from the last element in the array to the first element the opposite Then we can add each element to a new array Summarize the solution as follows Iterate over every element in our arrayIteration will start from the last to the first Add each element to a new array Full code Arraylet myArray Create new arraylet result Iterate over every element in our arrayfor let i myArray length i gt i Add every element to new array result push myArray i Result console log result Output Thank you for readingThank you for reading my blog 2022-12-07 06:31:31
海外TECH DEV Community Why using just console.log in 2023 is a big no-no 🚀 https://dev.to/naubit/why-using-just-consolelog-in-2023-is-a-big-no-no-2429 Why using just console log in is a big no no Here are must know console object methods and tricks Are you still using console log for all your JavaScript debugging needs in It s time to upgrade your skills and discover the full power of the JavaScript console object From console table to console time these advanced methods and tricks will help you improve the quality and readability of your debug output and make it easier to troubleshoot and fix problems in your code So why not join the ranks of the JavaScript ninja debuggers in and learn these essential techniques Your code will thank you The problemOne of the biggest problems with using just console log is that it can clutter up your code and make it difficult to read Additionally it s not very informative on its own It just outputs the value of whatever you pass to it without any context or additional information With that in mind here are ten JavaScript console object methods and tricks you should know about and give them a try I know it is faster to just console log but it can make your debugging experience way better do it for your future yourself ️⃣console tableThis method allows you to output tabular data in a readable and easy to understand format Instead of just logging out an array or object console table will display the data in a tabular format which makes it easier to scan and understand Output an array of objects as a tableconst users id name John Doe id name Jane Doe console table users This will output the users array in a tabular format with the properties of each object as columns and the objects as rows ️⃣console groupconsole group and console groupEnd These methods allow you to create a nested collapsible group in the console This can be useful for organizing and structuring your debug output so you can easily see what s happening at different levels of your code console group User Details console log Name John Doe console log Age console groupEnd This will create a nested collapsible group in the console with the heading “User Details The log messages inside the group will be indented and grouped together ️⃣console timeconsole time and console timeEnd These methods allow you to measure the amount of time it takes for a block of code to execute This can be useful for identifying performance bottlenecks in your code and optimizing them console time Fetching data fetch then response gt response json then data gt console timeEnd Fetching data Process the data This will measure the amount of time it takes to fetch data from the specified URL and parse the JSON response The elapsed time will be output in the console ️⃣console assertThis method allows you to write assertions in your code which are statements that should always be true If an assertion fails console assert will output an error message in the console This can be useful for catching bugs and ensuring your code is working as expected function add a b return a b Test the add functionconst result add console assert result Expected This will output an error message in the console if the add function does not return the expected result of when given the input and ️⃣Style your logsUse the console object to output styles and colors The console object allows you to output text in different colors and styles making your debug output more readable and easier to understand You can use the c placeholder in your console log statements to specify a CSS style for the output text console log cHello world color red font weight bold This will output the text “Hello world in red and bold using the specified CSS style By the way if you want even better logs you might want to use a specialized logging library which offers more settings I added a really good one in this article I wrote ️⃣console traceUse the console trace method to output a stack trace This can be useful for understanding the flow of execution in your code and for identifying where a particular log message is coming from function foo console trace function bar foo bar This will output a stack trace in the console showing the sequence of function calls leading up to the console trace call The output will look something like this ️⃣console dirUse the console dir method to output the properties of an object in a hierarchical format This can be useful for exploring the structure of an object and for seeing all of its properties and methods const obj id name John Doe address street Main St city New York zip console dir obj This will output the properties of the obj object in a hierarchical format allowing you to see the structure of the object and all of its properties and values ️⃣console countUse the console count method to count the number of times a specific log message is an output This can be useful for keeping track of how many times a particular code path is executed and for identifying hot spots in your code function foo x console count x foo hello foo world foo hello This will output the string “hello in the console followed by the number It will then output the string “world in the console followed by the number Finally it will output the string “hello again followed by the number since it has been called twice ️⃣console clearUse the console clear method to clear the console output This can be useful for keeping your debug output organized and uncluttered and for making it easier to focus on the information you re interested in console log Hello world console clear console log This log message will appear after the console is cleared This will output the string “Hello world in the console followed by a blank line since the console is cleared It will then output the string “This log message will appear after the console is cleared ️⃣️⃣console profileUse the console profile and console profileEnd methods to measure the performance of a block of code This can be useful for identifying performance bottlenecks and for optimizing your code for speed and efficiency console profile MyProfile Run some code that you want to measure the performance offor let i i lt i Do something console profileEnd MyProfile This will start profiling the block of code between the console profile and console profileEnd calls and will output the results in the console when the console profileEnd call is executed The output will include details about the amount of time it took to execute the code and any other performance related information Some final thoughtsIn don t just settle for console log there are many more powerful and valuable tools and techniques available in the JavaScript console object From console table to console time these methods and tricks will help you improve the quality and readability of your debug output and make it easier to troubleshoot and fix problems in your code So why not level up your debugging skills in and give these techniques a try Your code and your sanity will thank you Oh and… Let s Connect Twitter thenaubit 2022-12-07 06:30:52
海外TECH DEV Community Rebases in Git and why you shouldn’t be afraid of them https://dev.to/how-to-dev/rebases-in-git-and-why-you-shouldnt-be-afraid-of-them-1fb5 Rebases in Git and why you shouldn t be afraid of themBeginners often experience several points of confusion about rebases when using Git what they arewhy people do themwhy pushes might fail after successful rebaseIn this article I ll provide answers to those questions In the meantime TL DR rebases are a way of making your crude commit history into something you ll want to share with the rest of your team How to do a rebaseTo perform a rebase you run git rebase lt commit reference gt Commit reference can be anythingーfor example branch name tag or commit id A rebase is a fairly complicated operation so let s walk through various aspects of it Simple rebaseIn its simplest form rebasing takes changes from one place one base and moves them to another It changes the spot where the history branched off So with the tree alias I wrote about previously we start with a branch graph like this git tree b HEAD gt test add test txt file abce origin main origin HEAD main Add lorem ipsum to readme edd Add readmeand we move our branch to start from a different placeーthe top of the main branch git rebase mainSuccessfully rebased and updated refs heads test and as a result we get a tree like this git tree fee HEAD gt test add test txt file abce origin main origin HEAD main Add lorem ipsum to readme edd Add readmeOur test branch used to start at edd Add readme and now it s starting at abce Add lorem ipsum to readme Rebase in progressEven a simple rebase may require additional input from your side For example you might have some conflict to resolve git rebase mainAuto merging test txtCONFLICT add add Merge conflict in test txterror could not apply b add test txt filehint Resolve all conflicts manually mark them as resolved withhint git add rm lt conflicted files gt then run git rebase continue hint You can instead skip this commit run git rebase skip hint To abort and get back to the state before git rebase run git rebase abort Could not apply b add test txt fileWhen checking the status in such a situation you will get an instruction from Git on how to proceed git statusinteractive rebase in progress onto abLast command done command done pick b add test txt fileNo commands remaining You are currently rebasing branch test on ab fix conflicts and then run git rebase continue use git rebase skip to skip this patch use git rebase abort to check out the original branch Unmerged paths use git restore staged lt file gt to unstage use git add lt file gt to mark resolution both added test txtno changes added to commit use git add and or git commit a You need to edit the file to resolve the conflict When you are done with it you add the change to staging git add test txt no output and you continue with the rebase git rebase continue detached HEAD bcad add test txt file file changed insertion Successfully rebased and updated refs heads test Subsequently Git will continue with the rebase it can finish smoothly as in my case or you may encounter more conflicts to resolve manually Rebase interactiveA more advanced option for rebase is rebase interactive It allows you to make very precise changes on the branchーnot just move it from one place to another Let s take a look at a few examples below Reword commitsThe simplest thing you can do is just change the commit message The good thing is that there is no chance of conflict because the files are left the same Squashing commitsYou can choose a few commits and turn them into one It preserves the file s changesーit just collapses a chain of changes into one commit It requires writing a new commit message for the new commit but on its own it will not cause conflicts Editing commitsYou can edit the file changes in the commit too This allows you to make sure the commits contain all the relevant changes If there are changes to the same places later in the branch then you will need to resolve conflicts manually Removing commitsAnother operation is removing commits from the branchーthe commit and its changes If there were additional modifications to the same code later in the branch removing the commit will cause some conflicts The most basic use case is when you realize that some changes are not needed and you want to remove them from the history Besides that I often use it when I realize my branch is getting too big and I intend to make it more focused and merge it sooner Reordering commitsYou can reorder commits as well There are situations in which it can make sense but it gets complicated quickly if you try to reorder a commit that changes the same area of code File interfaceAs you can see interactive rebasing requires a lot of subtle input Git gets this input in the form of a text file When I run git rebase main i I get my editor with the following content pick ab add test txt Rebase abce ab onto abce command Commands p pick lt commit gt use commit r reword lt commit gt use commit but edit the commit message e edit lt commit gt use commit but stop for amending s squash lt commit gt use commit but meld into previous commit f fixup C c lt commit gt like squash but keep only the previous commit s log message unless C is used in which case keep only this commit s message c is same as C but opens the editor x exec lt command gt run command the rest of the line using shell b break stop here continue rebase later with git rebase continue d drop lt commit gt remove commit l label lt label gt label current HEAD with a name t reset lt label gt reset HEAD to a label m merge C lt commit gt c lt commit gt lt label gt lt oneline gt create a merge commit using the original merge commit s message or the oneline if no original merge commit was specified use c lt commit gt to reword the commit message These lines can be re ordered they are executed from top to bottom If you remove a line here THAT COMMIT WILL BE LOST However if you remove everything the rebase will be aborted When you save the file and exit the editor Git will follow the instructions you provided there It s an interface that can feel awkward at first but one can get used to it pretty quickly The only “gotcha is that you need to know your default editor and know how to use it I ve written a bit more about it in a section of another article Practical tipWhile doing interactive rebasing try to do one thing at the time Git can manage to do the following in one rebase change the branch starting point reorder some commits squash othersetc However you ll probably get lost in all the conflicts that will happen all at once It s easier to do one thing at the time and keep the following order remove superfluous commits first squash related commits and thenmove the branch to another base In this way you reduce the number of commits that have to be moved aroundーthereby reducing the number of conflicts you must resolve History changesRebasing changes the history of the repository This means that the same changes will appear as different commits on different branches It s not a mistake but it can be confusing when you see the following logs for the first time git push origin testTo github com how to js git md git rejected test gt test non fast forward error failed to push some refs to github com how to js git md git hint Updates were rejected because the tip of your current branch is behindhint its remote counterpart Integrate the remote changes e g hint git pull before pushing again hint See the Note about fast forwards in git push help for detailsnon fast forward means there is no direct route way for one point in the repository history toward another In this case you need to integrate remote and local changes yourself There are some subtleties to getting branches in sync and it s a topic for another article Depending on the workflow in your project it can be forbidden or required to override the history of some branches The workflow I use prohibits history changes to the master main branch and it requires rebases of all the other branches There are no right or wrong approaches to rebasing each policy has its pros and cons but it s likely that your team will insist that you maintain consistency with the selected approach Possible side effectsBesides the intrinsic complexity of rebases they introduce some challenges in team environments local only branchesWhen your work is on your computer only it s always safe to rebase or change the history in any other way It s a good practice because it always helps you to clean up your work before others can see it If you started some work a month ago and since then you ve made changes to main regularlyーit s not worth preserving information with commits such as Merge remote tracking branch origin main into test Instead you can rebase regularly and keep history as a straight line Branches that were uploaded to remoteOnce you share your branch any change to its history can break stuff For example your continuous integration CI will remember the results of a test run of a commit but the commit will be gone I ve met people who are very cautious about changing a history that was already shared so I guess there are teams where this might be discouraged Remote branches that other works onThe most complicated case is to change the history of a branch that other people are working on For that I would recommend making sure everybody is up to date when the change happensーthat there are no two people introducing changes to the branch at the same time getting everyone updated to the new rebased branch before they start the new work in it This is a delicate situation because it breaks a lot of the automated conflict resolution Git employs It s good to be careful in such cases and make sure everybody knows what s happening Keep on learningIf you are interested in learning more about branches in Git a great and pretty resource is available at Learn Git Branching If you are interested in learning more about Git sign up here to get updates about my Git focused content 2022-12-07 06:10:37
海外TECH DEV Community Build a Blog API With JWT Authentication Using Django Rest Framework https://dev.to/documatic/build-a-blog-api-with-jwt-authentication-using-django-rest-framework-3718 Build a Blog API With JWT Authentication Using Django Rest FrameworkDjango REST framework is a powerful and flexible toolkit for building Web APIs You can easily build a REST API using DRF and consume the endpoints from a React Angular or other Frontend application DRF provides a lot of features out of the box to make the development process easier and faster In this tutorial we will build a blog API with the following features Custom user model where email is the unique identifier instead of email JWT based authentication Ability to create retrieve update and delete posts Like Dislike feature for posts Ability to comment on posts Note If you encounter any issues throughout the tutorial you can check out the code in the GitHub repository Table of ContentsPrerequisiteProject ConfigurationCustom User Model in Django for Email Based AuthUser ProfileJWT AuthenticationUser Registration and Login EndpointsThe Blog API Prerequisite This guide assumes that you have intermediate level knowledge of Django and Django Rest Framework Project Configuration First create a virtual environment and activate it python m venv venvsource venv bin activateNext install Django and create a new Django project pip install django django admin startproject config Custom User Model in Django for Email Based Auth One of the things that make Django really great is its built in User model that comes with username based authentication In no time you can have authentication that works out of the box However not all projects need username and password pair for authentication or in some cases you might want to include additional fields in the built in User model Either way you are in luck because Django also provides room for customization In this tutorial we will tweak the default User model to use email as the unique primary identifier of users instead of a username Other use cases for a custom user model include Including other unique fields for authentication like a phone number To stack all user information be it auth related or non auth fields all in the User model Alright let s now create an app named users that will contain the logic we just talked about py manage py startapp usersAdd it to the installed apps list in the settings INSTALLED APPS django contrib admin django contrib auth django contrib contenttypes django contrib sessions django contrib messages django contrib staticfiles Local apps users There are two ways you can customize the User model Either by extending from AbstractUser or AbstractBaseUserWhat s the difference and when should you use one over the other Glad you asked AbstractUser Are you satisfied with the existing fields in the built in User model but do you want to use email as the primary unique identifier of your users or perhaps remove the username field or do you want to add fields to the existing User If yes  AbstractUser is the right option for you AbstractBaseUser This class contains authentication functionality but no fields so you have to add all the necessary fields when you extend from it You probably want to use this to have more flexibility on how you want to handle users Note If you re starting a new project it s highly recommended to set up a custom user model even if the default User model is sufficient for you This model behaves identically to the default user model but you ll be able to customize it in the future if the need arises from django contrib auth models import AbstractUserclass User AbstractUser passCustom Model ManagerA Manager is a class that provides an interface through which database query operations are provided to Django models You can have more than one manager for your model Consider this model from django db import modelsclass Car models Model passTo get all instances of Car you will use Car objects all objects is the default name that Django managers use To change this name you can do the following from django db import modelsclass Car models Model cars models Manager Now to get all instances of car you should use Car cars all For our custom user model we need to define a custom manager class because we are going to modify the initial Queryset that the default Manager class returns We do this by extending from BaseUserManager and providing two additional methods create user and create superuser Create a file named managers py inside the users app and put the following users managers pyfrom django contrib auth base user import BaseUserManagerfrom django utils translation import gettext lazy as class CustomUserManager BaseUserManager Custom user model manager where email is the unique identifier for authentication instead of usernames def create user self email password extra fields if not email raise ValueError Users must have an email address email self normalize email email user self model email email extra fields user set password password user save return user def create superuser self email password extra fields extra fields setdefault is staff True extra fields setdefault is superuser True extra fields setdefault is active True if extra fields get is staff is not True raise ValueError Superuser must have is staff True if extra fields get is superuser is not True raise ValueError Superuser must have is superuser True return self create user email password extra fields Then create the custom user model as follows users models pyfrom django contrib auth models import AbstractUserfrom django utils translation import gettext lazy as from managers import CustomUserManagerclass CustomUser AbstractUser email models EmailField email address unique True USERNAME FIELD email REQUIRED FIELDS username objects CustomUserManager def str self return self emailUSERNAME FIELD specifies the name of the field on the user model that is used as the unique identifier In our case it s email REQUIRED FIELDS A list of the field names that will be prompted when creating a superuser via the createsuperuser management command This doesn t have any effect in other parts of Django like when creating a user in the admin panel Next we need to tell Django about the new model that should be used to represent a User This is done as follows config settings pyAUTH USER MODEL users CustomUser Finally create and apply migrations py manage py makemigrationspy manage py migrateFormsYou need to extend Django s built in UserCreationForm and UserChangeForm forms so that they can use the new user model that we are working with Create a file named forms py inside the users app and add the following users forms pyfrom django contrib auth forms import UserChangeForm UserCreationFormfrom models import CustomUserclass CustomUserCreationForm UserCreationForm class Meta model CustomUser fields email class CustomUserChangeForm UserChangeForm class Meta model CustomUser fields email AdminTell the admin panel to use these forms by extending from UserAdmin in users admin py users admin pyfrom django contrib import adminfrom django contrib auth admin import UserAdminfrom forms import CustomUserChangeForm CustomUserCreationFormfrom models import CustomUser admin register CustomUser class CustomUserAdmin UserAdmin add form CustomUserCreationForm form CustomUserChangeForm model CustomUser list display username email is active is staff is superuser last login list filter is active is staff is superuser fieldsets None fields username email password Permissions fields is staff is active is superuser groups user permissions Dates fields last login date joined add fieldsets None classes wide fields username email password password is staff is active search fields email ordering email add form and form specify the forms to add and change user instances fieldsets specify the fields to be used in editing users and add fieldsets specify fields to be used when creating a user And that s all you need You can now go to the admin panel and add edit users User Profile Let s now create a user profile This includes non auth related fields for the user For now this model contains an avatar and bio You must already be familiar with modeling a profile for the user Basically this is done by using a one to one relationship between the User and Profile model In a one to one relationship one record in a table is associated with one and only one record in another table using a foreign key For example a user model instance is associated with one and only one profile instance Head over to users models py and add the following users models pyimport osfrom django conf import settingsfrom django db import modelsfrom django template defaultfilters import slugifydef get image filename instance filename name instance product name slug slugify name return f products slug filename class Profile models Model user models OneToOneField settings AUTH USER MODEL on delete models CASCADE avatar models ImageField upload to get image filename blank True bio models CharField max length blank True def str self return self user email property def filename self return os path basename self image name Whenever you are using an ImageField in Django you need to install Pillow which is one of the most common image processing libraries in Python Let s install it pip install pillow Next let s register the profile model in line with the custom user model as follows users admin pyfrom django contrib import adminfrom django contrib auth admin import UserAdminfrom forms import CustomUserChangeForm CustomUserCreationFormfrom models import CustomUser Profileclass ProfileInline admin StackedInline model Profile can delete False verbose name plural Profile admin register CustomUser class CustomUserAdmin UserAdmin add form CustomUserCreationForm form CustomUserChangeForm model CustomUser list display username email is active is staff is superuser last login list filter is active is staff is superuser fieldsets None fields username email password Permissions fields is staff is active is superuser groups user permissions Dates fields last login date joined add fieldsets None classes wide fields username email password password is staff is active search fields email ordering email inlines ProfileInline admin site register Profile Since we are working with user uploaded images we need to set MEDIA URL and MEDIA ROOT in the settings config settings pyMEDIA ROOT os path join BASE DIR media MEDIA URL media Next configure the project s urls py to serve user uploaded media files during development config urls pyfrom django conf import settingsfrom django conf urls static import staticurlpatterns static settings MEDIA URL document root settings MEDIA ROOT Before testing this out let s create a signal to automatically create a user profile when a user is created Create a file named signals py and add the following users signals pyfrom django contrib auth import get user modelfrom django db models signals import post savefrom django dispatch import receiverfrom models import ProfileUser get user model receiver post save sender User def create profile sender instance created kwargs if created Profile objects create user instance receiver post save sender User def save profile sender instance kwargs instance profile save Finally connect the receivers in the ready method of the app s configuration by importing the signals module Head over to users apps py and add the following users apps pyfrom django apps import AppConfigclass UsersConfig AppConfig default auto field django db models BigAutoField name users def ready self import users signalsTest it out py manage py makemigrationspy manage py migratepy manage py runserver JWT Authentication The default authentication system that Django provides is session based Sessions in Django are implemented using the django contrib sessions middleware SessionMiddleware middleware This session based auth works well with the traditional HTML request response cycle However if you have a client that expects the server to return a JSON response instead of an HTML you are going to have to use token authentication or JWT authentication and let the client decide what to do with the JSON response In this tutorial we will implement JWT authentication using Django Rest Framework What is JWT JSON Web Token JWT is a cryptographically signed URL safe token for securely transmitting information between parties as a JSON object In JWT based auth the following happens The client sends the username and password to the server The server validates user credentials against the database The server generates and sends to the client a secure JWT token that is signed using a secret key This token is of the format header payload signatureDecoding tokens in the above format will give information about the user like ID username etc The client then includes this token in the HTTP header for subsequent requests The server verifies the token using the secret key without hitting the database If the token has been tampered with the client s request will be rejected This token also called access token although customizable is usually short lived Along with the access token the server also generates and sends to the client a refresh token A refresh token has a longer life and you can exchange it for an access token JWT thus is scalable and fast because of fewer database hits Alright let s first install Django Rest Framework pip install djangorestframework Add it to installed apps settings config settings pyINSTALLED APPS rest framework To implement JWT auth in our project we are going to make use of djangorestframework simplejwt Install it pip install djangorestframework simplejwt Then tell DRF the authentication backend we want to use config settings pyREST FRAMEWORK DEFAULT AUTHENTICATION CLASSES rest framework simplejwt authentication JWTAuthentication Here are a couple of setting variables for simple JWT that can be customized in the settings config settings pyfrom datetime import timedeltaSIMPLE JWT ACCESS TOKEN LIFETIME timedelta minutes REFRESH TOKEN LIFETIME timedelta days ROTATE REFRESH TOKENS True BLACKLIST AFTER ROTATION True UPDATE LAST LOGIN False ALGORITHM HS SIGNING KEY SECRET KEY VERIFYING KEY None AUDIENCE None ISSUER None JWK URL None LEEWAY AUTH HEADER TYPES Bearer AUTH HEADER NAME HTTP AUTHORIZATION USER ID FIELD id USER ID CLAIM user id USER AUTHENTICATION RULE rest framework simplejwt authentication default user authentication rule AUTH TOKEN CLASSES rest framework simplejwt tokens AccessToken TOKEN TYPE CLAIM token type JTI CLAIM jti SLIDING TOKEN REFRESH EXP CLAIM refresh exp SLIDING TOKEN LIFETIME timedelta minutes SLIDING TOKEN REFRESH LIFETIME timedelta days If ROTATE REFRESH TOKENS is set to True a new refresh token will be returned along with the access token And if BLACKLIST AFTER ROTATION is set to True refresh token submitted to the refresh view will be added to the blacklist You need to add  rest framework simplejwt token blacklist to the list of installed apps for the BLACKLIST AFTER ROTATIONsetting to work so let s do that config settings py Third party appsINSTALLED APPS rest framework simplejwt token blacklist Finally run the following command to apply the app s migrations py manage py migrateNow we need to create access and refresh tokens when the user registers login In the next section we will add serializer and views to accomplish this task User Registration and Login Endpoints Create a file named serializers py inside the users app and add the following users serializers pyfrom django contrib auth import authenticatefrom rest framework import serializersfrom models import CustomUser Profileclass CustomUserSerializer serializers ModelSerializer Serializer class to serialize CustomUser model class Meta model CustomUser fields id username email class UserRegisterationSerializer serializers ModelSerializer Serializer class to serialize registration requests and create a new user class Meta model CustomUser fields id username email password extra kwargs password write only True def create self validated data return CustomUser objects create user validated data class UserLoginSerializer serializers Serializer Serializer class to authenticate users with email and password email serializers CharField password serializers CharField write only True def validate self data user authenticate data if user and user is active return user raise serializers ValidationError Incorrect Credentials class ProfileSerializer CustomUserSerializer Serializer class to serialize the user Profile model class Meta model Profile fields bio class ProfileAvatarSerializer serializers ModelSerializer Serializer class to serialize the avatar class Meta model Profile fields avatar Note that we have also created a serializer class for the profile Then in the views py users views pyfrom django contrib auth import get user modelfrom rest framework import statusfrom rest framework generics import GenericAPIView RetrieveUpdateAPIViewfrom rest framework permissions import AllowAny IsAuthenticatedfrom rest framework response import Responsefrom rest framework simplejwt tokens import RefreshTokenfrom import serializersfrom models import ProfileUser get user model class UserRegisterationAPIView GenericAPIView An endpoint for the client to create a new User permission classes AllowAny serializer class serializers UserRegisterationSerializer def post self request args kwargs serializer self get serializer data request data serializer is valid raise exception True user serializer save token RefreshToken for user user data serializer data data tokens refresh str token access str token access token return Response data status status HTTP CREATED class UserLoginAPIView GenericAPIView An endpoint to authenticate existing users using their email and password permission classes AllowAny serializer class serializers UserLoginSerializer def post self request args kwargs serializer self get serializer data request data serializer is valid raise exception True user serializer validated data serializer serializers CustomUserSerializer user token RefreshToken for user user data serializer data data tokens refresh str token access str token access token return Response data status status HTTP OK class UserLogoutAPIView GenericAPIView An endpoint to logout users permission classes IsAuthenticated def post self request args kwargs try refresh token request data refresh token RefreshToken refresh token token blacklist return Response status status HTTP RESET CONTENT except Exception as e return Response status status HTTP BAD REQUEST class UserAPIView RetrieveUpdateAPIView Get Update user information permission classes IsAuthenticated serializer class serializers CustomUserSerializer def get object self return self request userclass UserProfileAPIView RetrieveUpdateAPIView Get Update user profile queryset Profile objects all serializer class serializers ProfileSerializer permission classes IsAuthenticated def get object self return self request user profileclass UserAvatarAPIView RetrieveUpdateAPIView Get Update user avatar queryset Profile objects all serializer class serializers ProfileAvatarSerializer permission classes IsAuthenticated def get object self return self request user profileThe above views are self explanatory Basically the views for user authentication use the RefreshToken class of simple JWT to generate and send to the client refresh and access tokens In addition the logout view blacklists the refresh token The other views are used to get or update a user and his her profile Now let s hook our views in the URLs Head over to config urls py and add the users app URLs config urls pyfrom django urls import include pathurlpatterns path include users urls namespace users Inside the users app create a file named urls py and add the endpoints as follows users urls pyfrom django urls import pathfrom rest framework simplejwt views import TokenRefreshViewfrom users import viewsapp name users urlpatterns path register views UserRegisterationAPIView as view name create user path login views UserLoginAPIView as view name login user path token refresh TokenRefreshView as view name token refresh path logout views UserLogoutAPIView as view name logout user path views UserAPIView as view name user info path profile views UserProfileAPIView as view name user profile path profile avatar views UserAvatarAPIView as view name user avatar Note that the token refresh endpoint will be used to get a new access and refresh token The Blog API First create an app named postspy manage py startapp postsand add it to the list of installed apps in the settings config settings pyINSTALLED APPS posts Let s wire up the models We are going to have models The Post Category and CommentA post can have many categories and comments thus we are going to use a ManyToMany field posts models pyfrom django conf import settingsfrom django db import modelsfrom django utils translation import gettext lazy as class Category models Model name models CharField Category name max length class Meta verbose name Category verbose name plural Categories def str self return self nameclass Post models Model title models CharField Post title max length author models ForeignKey settings AUTH USER MODEL related name posts null True on delete models SET NULL categories models ManyToManyField Category related name posts list blank True body models TextField Post body likes models ManyToManyField settings AUTH USER MODEL related name post likes blank True created at models DateTimeField auto now add True updated at models DateTimeField auto now True class Meta ordering created at def str self return f self title by self author username class Comment models Model post models ForeignKey Post related name comments on delete models CASCADE author models ForeignKey settings AUTH USER MODEL related name post comments null True on delete models SET NULL body models TextField Comment body created at models DateTimeField auto now add True updated at models DateTimeField auto now True class Meta ordering created at def str self return f self body by self author username Now register these models in the admin posts admin pyfrom django contrib import adminfrom models import Category Comment Postadmin site register Category admin site register Post admin site register Comment Create and run migrations py manage py makemigrationspy manage py migrateGreat let s now set up the serializer classes and views Create serializers py inside the posts app and add the following posts serializers pyfrom rest framework import serializersfrom models import Category Comment Postclass CategoryReadSerializer serializers ModelSerializer class Meta model Category fields all class PostReadSerializer serializers ModelSerializer author serializers CharField source author username read only True categories serializers SerializerMethodField read only True likes serializers SerializerMethodField read only True class Meta model Post fields all def get categories self obj categories list cat name for cat in obj categories get queryset only name return categories def get likes self obj likes list like username for like in obj likes get queryset only username return likesclass PostWriteSerializer serializers ModelSerializer author serializers HiddenField default serializers CurrentUserDefault class Meta model Post fields all class CommentReadSerializer serializers ModelSerializer author serializers CharField source author username read only True class Meta model Comment fields all class CommentWriteSerializer serializers ModelSerializer author serializers HiddenField default serializers CurrentUserDefault class Meta model Comment fields all Separating serializers for read and write is something that can be really helpful because you may sometimes want to include more details in the response for read list and retrieve but limit the number of fields when adding an entry to the database This makes your serializer classes less complicated Also note the use of serializers CurrentUserDefault This is really hand in to automatically set the authenticated user as the author or owner of something Next to write our views we are going to use ViewSets If you are new to ViewSets here is a quick overview ViewSet is a type of class based view that combines the logic for a set of related views into a single class The most common types of ViewSets that you are most likely to use are Modelviewset and ReadOnlyModelViewSet One of the main advantages of ViewSets is to have URL endpoints automatically defined for you through RoutersViewSets have the highest level of abstraction and you can use them to avoid writing all the code for basic and repetitive stuff They are a huge time saver That being said add the following code in the views and read the comments for further explanation posts views pyfrom django shortcuts import get object or from rest framework import permissions status viewsetsfrom rest framework response import Responsefrom rest framework views import APIViewfrom posts models import Category Comment Postfrom posts serializers import CategoryReadSerializer CommentReadSerializer CommentWriteSerializer PostReadSerializer PostWriteSerializer from permissions import IsAuthorOrReadOnly Category is going to be read only so we use ReadOnlyModelViewSetclass CategoryViewSet viewsets ReadOnlyModelViewSet List and Retrieve post categories queryset Category objects all serializer class CategoryReadSerializer permission classes permissions AllowAny class PostViewSet viewsets ModelViewSet CRUD posts queryset Post objects all In order to use different serializers for different actions you can override the get serializer class self method def get serializer class self if self action in create update partial update destroy return PostWriteSerializer return PostReadSerializer get permissions self method helps you separate permissions for different actions inside the same view def get permissions self if self action in create self permission classes permissions IsAuthenticated elif self action in update partial update destroy self permission classes IsAuthorOrReadOnly else self permission classes permissions AllowAny return super get permissions class CommentViewSet viewsets ModelViewSet CRUD comments for a particular post queryset Comment objects all def get queryset self res super get queryset post id self kwargs get post id return res filter post id post id def get serializer class self if self action in create update partial update destroy return CommentWriteSerializer return CommentReadSerializer def get permissions self if self action in create self permission classes permissions IsAuthenticated elif self action in update partial update destroy self permission classes IsAuthorOrReadOnly else self permission classes permissions AllowAny return super get permissions Here we are using the normal APIView classclass LikePostAPIView APIView Like Dislike a post permission classes permissions IsAuthenticated def get self request pk user request user post get object or Post pk pk if user in post likes all post likes remove user else post likes add user return Response status status HTTP OK We haven t created custom permission to limit edit and delete actions to the owner of a post so let s go ahead and do that Create a file named permissions py inside the posts app and add the following posts permissions pyfrom rest framework import permissionsclass IsAuthorOrReadOnly permissions BasePermission Check if authenticated user is author of the post def has permission self request view return request user is authenticated is True def has object permission self request view obj if request method in permissions SAFE METHODS return True return obj author request userFinally let s configure the URLs config urls pyfrom django urls import include pathurlpatterns path post include posts urls namespace posts posts urls pyfrom django urls import include pathfrom rest framework routers import DefaultRouterfrom views import CategoryViewSet CommentViewSet LikePostAPIView PostViewSetapp name posts router DefaultRouter router register r categories CategoryViewSet router register r P lt post id gt d comment CommentViewSet router register r PostViewSet urlpatterns path include router urls path like lt int pk gt LikePostAPIView as view name like post Great that s all You can use Postman or the built in browsable API to test the endpoints Note that if you use the browsable API you need to add session authentication to the DEFAULT AUTHENTICATION CLASSES because the browsable API uses session authentication for the login form To do so head over to the settings and update the DEFAULT AUTHENTICATION CLASSES setting config settings pyREST FRAMEWORK DEFAULT AUTHENTICATION CLASSES rest framework simplejwt authentication JWTAuthentication rest framework authentication SessionAuthentication Then in the project s urls py file add the API URL config urls pyfrom django urls import include pathurlpatterns path api auth include rest framework urls P S don t forget to configure CORS to allow in browser requests from other origins like your React app for example Happy coding 2022-12-07 06:10:28
海外TECH DEV Community 9 Things to Consider When Choosing an SCA Tool https://dev.to/gitguardian/9-things-to-consider-when-choosing-an-sca-tool-2h4n Things to Consider When Choosing an SCA ToolIn the past the development of software was something that required a lot of effort and resources Basically every piece of code was developed in house and code reuse was quite limited The situation is now the opposite Open source packages are so widely used that they make up the bulk of the total amount of software produced by passionate hobbyists and virtually all the software professionals in tech companies The convenience of reusing and fine tuning components made open source is just too strong for most software engineers to ignore it and keep reinventing the wheel To get a better idea of how big open source has become we have some recent insights according to a survey from Gartner over of the respondents stated that they rely on open source components In another report from Synopsis of the audited codebases contained at least one open source component and of the source code came from open source The report also noted that of the audited codebases contained components more than four years out of date This last data reveals the growing concern about the reliability and security of all this open source material found in private code bases Packages that are not maintained anymore cannot be patched for recently discovered vulnerabilities Therefore it s become critical for organizations to be able to inventory open source components and assess their vulnerabilities making the use of software composition analysis mandatory But not all SCA tools are created equal This blog post will provide eight factors to consider when choosing an SCA tool What is SCA Software Composition Analysis SCA is the process of analyzing an application s dependencies to determine if it is affected by known security vulnerabilities Organizations can more effectively manage security risks by understanding the dependencies between components SCA can be performed either manually or using automated tools Manual SCA is not scalable as the engineers must constantly check a vulnerability database such as NVD National Vulnerability Database maintained by NIST and then compare the vulnerable versions with their existing dependencies Much more efficient is to use automated SCA scanning tools which can be triggered manually or integrated into the CI CD pipeline for continuous checks Importance of Software Composition AnalysisSCA is integral to application security as it helps identify and mitigate risks associated with using third party components SCA can help identify vulnerabilities in third party components that attackers could exploit It can also help track the versions of third party components and ensure that they are up to date By keeping track of the components used in an application SCA can also help ensure compliance with license and security policies In short SCA is an essential part of the code security toolkit focused on third party components How is SCA different from SAST SAST is a software testing technique that involves analyzing the source code of a software application to identify potential security vulnerabilities such as injection attacks cross site scripting XSS improper error handling and insecure use of cryptographic functions SAST aims to identify security vulnerabilities early in the software development cycle to mitigate them before the application is compiled and deployed While SAST is an analysis technique used to check for known vulnerabilities in source code SCA is used to scan dependencies for security vulnerabilities and license issues Both are usually performed pre build against source code or post build against binaries as they don t require an application s execution to identify potential vulnerabilities Both are equally important in ensuring the security of a software application How to Choose an SCA tool The many SCA tools on the market today can make it hard to decide which is the right one for your needs To help you select the right one we have curated a list of things you should look out for in an SCA tool Language SupportWhen opting for an SCA tool it s vital to check what all languages are supported by the tool Software composition analysis is language end even ecosystem dependent package managers build system etc for instance most SCA tools rely on lock files such as package lock json or Pipfile lock to find dependencies and their respective versions So you need to be careful here Accessible to Use Developer FriendlinessThe SCA tool you choose should make your life easier not harder It should be intuitive and easy to use so that you can focus on your work not on learning the tool It should also be developer friendly so that you can easily integrate it into your existing development process Also it should be scalable to grow with your organization The vendor should also have proper technical documentation available for the developers and having technical support for the tool is always a plus Support for Binary scanningWhen looking for a Software Composition Analysis SCA tool choosing one that supports the scanning of binary files is essential Many SCA tools don t support this type of scanning which can leave vulnerabilities in the binaries used by the developers unchecked Scanning binary files such as wheel files whl are essential because it can find vulnerabilities that would otherwise be missed by scanning the dependencies If you are not doing binary scanning used by your developers you are not getting the complete picture of your code s security Direct vs Transitive DependenciesThere are two types of dependencies in software development direct and transitive A direct dependency is when one piece of software directly depends on another piece of software For example if software A directly uses software B then A has a direct dependency on B Conversely if software A uses software B and software B uses software C then A has a transitive dependency on C The SCA tool should be able to provide you with the information if the vulnerability is in the direct dependency or transitive dependency This is important because both types of dependencies can pose a security threat to a software project False positives False negativesIf you are not familiar with the concept of false positives and false negatives you should read this article about accuracy precision and recall In a nutshell false positives are vulnerabilities wrongly flagged as such by the tool and false negatives are genuine vulnerabilities that the detection tool silently skipped This is an important factor to consider when choosing a software composition analysis tool because false positives can lead to wasted time and resources Developers may spend a significant amount of time manually reviewing and investigating these results even though most are not security threats This also known as alert fatigue can be frustrating for developers and decrease their trust in the tool potentially leading them to ignore or not use the tool as frequently as they otherwise would The numbers reported by vendors can be challenging to verify The best way to ensure that an SCA tool can accurately identify security threats while minimizing the number of false positives is to test it for free when possible Webhooks amp API SupportWhen looking for an SCA tool it s essential to check if the tool has proper API and webhook support so that you can easily integrate it into your CI CD pipeline Having proper API and webhook support will allow you to automate SCA scanning as part of your CI CD process which will help ensure that your applications are always up to date and compliant with security standards Without proper API and webhook support you may have to manually trigger SCA scans which can lead to delays in your pipeline Rich Vulnerability DatabaseA good SCA vendor should have a rich vulnerability database to detect vulnerabilities in your open source packages Such a database would enable the SCA vendor to provide you with customized alerts and recommendations on the best way to fix the identified vulnerabilities In addition the SCA vendor should have a team of expert analysts who can help you understand the nature of the vulnerabilities and their potential impact on your organization in case you need any support Time to Onboard New CVEsSCA tools are used by many organizations to keep track of vulnerabilities and potential security risks It s essential to check how much time the SCA tool takes to onboard new CVEs on their platform from the vulnerability database This allows organizations to plan for and respond to new security risks promptly Additionally it helps to ensure that SCA tools are up to date and provide accurate information about the latest security threats Detailed Reporting RemediationThe scanning should provide detailed reporting that helps the security team understand the scan results of the open source packages The report should include a list of all the packages that were scanned as well as the results of the scan includingVulnerability descriptionCVSS scoreCVSSv scoreVersion impactedThe SCA tool should also provide proper remediation steps so that the developers can fix the issues ConclusionOpen source has become the norm in the software development world with nearly of companies using open source software in some form or another For many companies open source is the preferred choice for software development due to its flexibility cost effectiveness and vast ecosystem of available tools and resources However with the increasing popularity of open source there is also an increase in the number of vulnerabilities of open source packages This can create several risks and challenges for companies including vulnerabilities in developed applications licensing issues and potential security breaches Having SCA tools in your build and deployment pipeline can help you avoid security risks that might arise from any open source dependency You should now be more informed about the important factors to consider before selecting such as tool 2022-12-07 06:02:36
金融 JPX マーケットニュース [OSE]TOPIX先物取引に係る中心限月取引の変更 https://www.jpx.co.jp/news/2020/20221207-02.html 限月 2022-12-07 15:20:00
金融 article ? The Finance NFTとは?わかりやすく解説【2022年12月最新版】 https://thefinance.jp/strategy/221207 sbinftmark 2022-12-07 06:29:06
海外ニュース Japan Times latest articles China eases COVID restrictions in major shift in virus policy https://www.japantimes.co.jp/news/2022/12/07/asia-pacific/china-major-covid-shift/ discontent 2022-12-07 15:11:27
海外ニュース Japan Times latest articles Yu Darvish joins Shohei Ohtani in agreeing to play in WBC https://www.japantimes.co.jp/sports/2022/12/07/baseball/ohtani-darvish-wbc-japan/ Yu Darvish joins Shohei Ohtani in agreeing to play in WBCThe year old Darvish was a member of Japan s second WBC championship team in Since then Samurai Japan was eliminated in the semifinals in 2022-12-07 15:11:05
ニュース BBC News - Home China eases Covid quarantine and lockdown measures https://www.bbc.co.uk/news/world-asia-china-63855508?at_medium=RSS&at_campaign=KARANGA centres 2022-12-07 06:27:18
ニュース BBC News - Home UK weather: People urged to heat main rooms as cold snap begins https://www.bbc.co.uk/news/uk-63879870?at_medium=RSS&at_campaign=KARANGA advise 2022-12-07 06:27:50
ニュース BBC News - Home 'The baby I lost to miscarriage saved my life' https://www.bbc.co.uk/news/uk-scotland-glasgow-west-63856070?at_medium=RSS&at_campaign=KARANGA hospice 2022-12-07 06:36:43
ニュース BBC News - Home Ukraine war: US neither encouraged nor enabled Kyiv to strike inside Russia - Blinken https://www.bbc.co.uk/news/world-europe-63882955?at_medium=RSS&at_campaign=KARANGA blinkenrussian 2022-12-07 06:01:22
ニュース BBC News - Home Cambridge: 'I nearly bought a stolen house on Zoopla' https://www.bbc.co.uk/news/uk-england-cambridgeshire-63871888?at_medium=RSS&at_campaign=KARANGA holland 2022-12-07 06:01:39
ビジネス ダイヤモンド・オンライン - 新着記事 エーザイ認知症薬に投資家沸く 効果には議論も - WSJ発 https://diamond.jp/articles/-/314138 議論 2022-12-07 15:24:00
ビジネス ダイヤモンド・オンライン - 新着記事 テスラの大型EVトラック、道のりは遠く - WSJ発 https://diamond.jp/articles/-/314139 道のり 2022-12-07 15:18:00
ニュース Newsweek 共産革命から経済大国へ──江沢民と中国の軌跡 https://www.newsweekjapan.jp/stories/world/2022/12/post-100286.php 指導者が開放的で、メディアや社会からの批判もある程度まで受け入れていた時代だから。 2022-12-07 15:27:12
仮想通貨 BITPRESS(ビットプレス) [日経] Web3に戸惑う大手企業 取引慣行や常識、通用せず https://bitpress.jp/count2/3_9_13482 大手企業 2022-12-07 15:27:20
IT 週刊アスキー 12月22日アプデ決定!『幻塔』Ver.2.2「鏡花月影」で新キャラ天琅も登場 https://weekly.ascii.jp/elem/000/004/116/4116434/ levelinfinite 2022-12-07 15:40:00
IT 週刊アスキー 観光やビジネスを快適にする滞在型ホテル「シタディーンハーバーフロント横浜」12月20日より宿泊予約の受付開始 https://weekly.ascii.jp/elem/000/004/116/4116392/ 公式サイト 2022-12-07 15:30:00
IT 週刊アスキー 【Amazonセール】7日の注目はデルの4Kモニターにモトローラのスマホ https://weekly.ascii.jp/elem/000/004/116/4116445/ amazon 2022-12-07 15:10:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)