投稿時間:2021-12-10 20:40:17 RSSフィード2021-12-10 20:00 分まとめ(46件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
TECH Engadget Japanese 球体ロボット型スピーカーの改良版。DIY対応バージョンも新登場「Gravastar Mars Pro」 https://japanese.engadget.com/gravastar-mars-pro-103552588.html 球体ロボット型スピーカーの改良版。 2021-12-10 10:35:52
TECH Engadget Japanese 最大70%オフのKindle本クリスマスセールが開催中! 2万タイトル以上が対象。12月25日まで https://japanese.engadget.com/kindle-christmas-sale-102038338.html amazon 2021-12-10 10:20:38
python Pythonタグが付けられた新着投稿 - Qiita Pythonのdatetime比較でハマった話 https://qiita.com/Hiroki1928/items/8911d08c2b02afc00c5b Pythonのdatetime比較でハマった話この記事について唐突ですが、以前作成した社内ボットが動かなくなりました。 2021-12-10 19:25:26
python Pythonタグが付けられた新着投稿 - Qiita Breast Cancer Datasetの列を入れ替える https://qiita.com/Ruo_Ando/items/c244fb890598aaa1b0e2 BreastCancerDatasetの列を入れ替えるからデータを入出するgtwgetStatusCodeStatusDescriptionOKContentRawContentHTTPOKAcceptRangesbytesContentLengthContentTypeapplicationxhttpdphpDateFriDecGMTETagecedfdcLastModifiedMonFebHeadersAcceptRangesbytesContentLengthContentTypeapplicationxhttpdphpDateFriDecGMTRawContentLengthAnacondaでwgetでファイルがとってこれない場合があるので、その場合はGUIからダウンロードするか、この辺りを参照する。 2021-12-10 19:16:28
js JavaScriptタグが付けられた新着投稿 - Qiita 【Vue.js】TodoList 編集機能を追加 https://qiita.com/Quest_love33/items/6cd3c1305e37ee6760aa 【Vuejs】TodoList編集機能を追加概要前回のtodoListに加えて編集できる機能を追加した。 2021-12-10 19:12:09
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 全角が1つでもあったらfalseを返したい https://teratail.com/questions/373248?rss=all 全角がつでもあったらfalseを返したい実現したいことJavaScriptで「全角がつでもあったらfalseを返したい」です。 2021-12-10 19:50:38
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Sparkのパーティションとワーカーの数の違いが分かりません https://teratail.com/questions/373247?rss=all 2021-12-10 19:47:50
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 【Rails】params単体で打つと値が入ってるのに、「params[:〇〇]」と打つとnilで返ってくる https://teratail.com/questions/373246?rss=all 【Rails】params単体で打つと値が入ってるのに、「params〇〇」と打つとnilで返ってくる以下がコードです。 2021-12-10 19:26:01
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) chromeとsafariで拡大縮小禁止したい https://teratail.com/questions/373245?rss=all chromeとsafariで拡大縮小禁止したい前提・実現したいことchromeとsafariでダブルタップをした時に、拡大縮小禁止したい。 2021-12-10 19:24:10
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) PHP iniファイル エラーが表示されない https://teratail.com/questions/373244?rss=all PHPiniファイルエラーが表示されない前提・実現したいこと意図的にエラーが発生するコードを書いても、サーバ上でエラーが表示されません。 2021-12-10 19:11:32
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 【c#】配列の何番目の要素が条件を満たしているのか知りたい https://teratail.com/questions/373243?rss=all 【c】配列の何番目の要素が条件を満たしているのか知りたい皆さんこんばんはcを勉強し始めて間もない者です。 2021-12-10 19:05:26
Ruby Rubyタグが付けられた新着投稿 - Qiita RailsアプリをHerokuデプロイでエラー https://qiita.com/mochi93kou/items/d9c64cae764c31748f2c GemfileにRubyのバージョンを宣言GemfilesourcegitsourcegithubreporepogitRubyの任意のバージョンを記載rubyGemfileを更新したのでbundleinstallを実行します。 2021-12-10 19:38:31
Ruby Rubyタグが付けられた新着投稿 - Qiita DeviseのUserテーブルにカラムを追加する https://qiita.com/makimaki2525/items/c0869cfbdf0146fde40f Deviseを使用する場合のモデル作成コマンド今回はUserモデルrailsgdeviseUser※通常のモデル作成コマンドrailsgmodelモデル名記述方法が違うので注意コマンドを実行すると作成されるファイルモデルUserマイグレーションファイルカラム任意のカラムを追加するユーザーネームを保存するためのカラムnameがないので追加します。 2021-12-10 19:19:14
AWS AWSタグが付けられた新着投稿 - Qiita [初学者向け]結局CIDRってなに? https://qiita.com/kmmz/items/bf059e17fecac746cc9e 私がAWSで初めてVPCを作成した際に、真っ先に躓いた部分がCIDRでした。 2021-12-10 19:57:59
GCP gcpタグが付けられた新着投稿 - Qiita Professional Data Engineerを受験したので結果と勉強方法をまとめました https://qiita.com/ptpt-free/items/8514eabee80fed99c0bf ユースケースに沿った問題といったものはないので、ほとんど択ですつ選びましょうみたいな問題は問程度また、セクションの部分の機械学習系は数問出ていましたので、自信がある人はチャレンジするといいかもしれないです自分は全くわからなくてひたすら首を捻っていましたで、試験結果は試験結果としては、なんとか合格しましたあまり自信がなく、ちょっとした記念受験感もあったので正直かなり驚きました。 2021-12-10 19:25:44
Ruby Railsタグが付けられた新着投稿 - Qiita RailsアプリをHerokuデプロイでエラー https://qiita.com/mochi93kou/items/d9c64cae764c31748f2c GemfileにRubyのバージョンを宣言GemfilesourcegitsourcegithubreporepogitRubyの任意のバージョンを記載rubyGemfileを更新したのでbundleinstallを実行します。 2021-12-10 19:38:31
Ruby Railsタグが付けられた新着投稿 - Qiita DeviseのUserテーブルにカラムを追加する https://qiita.com/makimaki2525/items/c0869cfbdf0146fde40f Deviseを使用する場合のモデル作成コマンド今回はUserモデルrailsgdeviseUser※通常のモデル作成コマンドrailsgmodelモデル名記述方法が違うので注意コマンドを実行すると作成されるファイルモデルUserマイグレーションファイルカラム任意のカラムを追加するユーザーネームを保存するためのカラムnameがないので追加します。 2021-12-10 19:19:14
技術ブログ Developers.IO AWS WAFだけで、Basic認証を設定してみた https://dev.classmethod.jp/articles/aws-waf-basic-auth/ awswaf 2021-12-10 10:00:48
海外TECH DEV Community AWS Karpenter - Is the AWS Open Source Kubernetes Autoscaler Right for You? https://dev.to/castai/aws-karpenter-is-the-aws-open-source-kubernetes-autoscaler-right-for-you-60c AWS Karpenter Is the AWS Open Source Kubernetes Autoscaler Right for You AWS has just made a new open source tool called Karpenter generally available I will dig into how it works and will be unavoidably comparing it with what we at CAST AI have built What exactly is Karpenter how does its autoscaling mechanism work and should you use it Karpenter is a very simple autoscaler with two reactive policies Its biggest selling point No node pools  Let s take a look at how Karpenter works and compare it to the autoscaling mechanisms of CAST AI Quick feature comparison CAST AI vs KarpenterDetailed feature comparison of Karpenter and CAST AIInstallation and onboardingAutoscaling policiesCloud vendor supportNo node poolsPod groupingCost optimizationKarpenter vs CAST AI which autoscaler is a better pick for you Installation and onboardingAfter trying Karpenter out I d say that onboarding isn t trivial but not as hard as the Kubernetes Cluster Autoscaler   Karpenter onboarding requires you to have eksctl CLI installed and configured even if you created an EKS cluster without the help of eksctl It takes around to steps to get started with KarpenterCAST AI doesn t have a eksctl dependency and you re looking at a steps process that your IT manager could complete on his own in a minute or two Autoscaling policiesKarpenter has only two most basic autoscaling policies At first glance they are quite similar to two of the policies in CAST AI Unscheduled Pod Policy and Node Deletion policy Let s compare the two Provisioner At its simplest form without sub features CAST AI s Unscheduled Pod Policy works in a similar way as Karpenter s Provisioner  If there are pods that can t start because no suitable node has been found by Kubernetes vanilla scheduler a new node will be created based on those pending pod constraints like zone subnet PodAntiAffinity capacity preference spot or on demand Karpenter has these constraints available for NodeSelector NodeAffinity TopologySpreadConstraints requirements key node ks aws instance type If not included all instance types are considered operator In values m large mxlarge key topology kubernetes io zone If not included all zones are considered operator In values us east a us east b key kubernetes io arch If not included all architectures are considered values arm amd key karpenter sh capacity type If not included the webhook for the AWS cloud provider will default to on demand operator In values spot on demand Karpenter supports GPU and ARM with the following tolerations nvidia com gpu amd com gpu and aws amazon com neuron To add a GPU node one needs to define a specific list of nodes and we re back to the node pool idea CAST AI allows you to specify more pod constraints like get me instances with fast local storage for Spark jobs but does not require you to specify the instance types yourself In case you didn t check lately there are available types on AWS which makes it easy getting back to implicit NodePools by accident You can also specify the Spot interruption rate per cluster and override per workload in CAST AI For example you may want your casual Spot workload in a cluster to be on more cost efficient Spot instances even if that means these instances could be interrupted once in a while But those huge Jupyter notebook pods with a ton of resources You want them to run Spot Instances that are so unpopular that they barely get ever interrupted Back to the Node Pools against own willRunning your Kubernetes workloads on burstable Ta Instance types is a crime to your business and your DevOps but this is what you will get by default with Karpenter Because as you guessed it they are the most affordable instances Don t want burstable instances Then list all acceptable Instance types in Karpenter Provisioner CRD which you want in your Kubernetes cluster to have And with that you have just specified a cherry picked Node list and are implicitly back to NodePools And what if these cherry picked Node lists are not available during Black Friday or Xmas days You will need to extend the list with more alternatives Many more alternatives But didn t the first paragraph in this article say there will be no Node Pools Unfortunately they are unavoidable with Karpenter under the hood Delete Empty Node policyAs the name implies Karpenter can and will delete empty nodes This policy allows you to set the Time To Live for empty nodes ttlSecondsAfterEmpty with a default of CAST AI s Delete Node policy works in the same fashion CAST AI engine will not remove nodes if there are workloads running on them excluding DaemonSets of course Kubernetes scheduler by default acts in a very fair way and will always distribute workloads for maximum performance and availability And if you re running EKS you can t change the Kubernetes scheduler profile Let s look at this with an analogyImagine a train Kubernetes cluster with train cars Nodes each train car can seat passengers pods the train has a capacity to transport passengers at peak The train moves from the central station fully utilized with seats taken and with every stop more people get off the train than on it Even a few stops before the end of the train journey if the train is carrying only passengers out of someone needs to make sure that there are empty train cars It s likely that there are to passengers in a train car enjoying their privacy and the Delete Empty Node train car can t find anything to remove So how does Karpenter help with over provisioned resources for off peak times when load is lower Enter Node ExpiryKarpenter offers a Node Expiry feature If a node expiry time to live value ttlSecondsUntilExpired is reached that node is drained of pods and Node is deleted Great But wait a minute what about your workloads that are running on these nodes Sorry end of shift Nodes are going down say hello to downtime Alright but how would you know what the expiration time should be If you get it too short your pods are going down you then have to wait several minutes for the Karpenter provisioner to add new nodes with refreshed ttlSecondsUntilExpired If you set ttlSecondsUntilExpired too long you re wasting your money In other words Karpenter reacts in time to add new capacity so your cloud bill could expand but leave you hanging with reducing that excess capacity CAST AI on the other hand offers Evictor that shrinks the cluster to the minimum number of nodes by bin packing pods simulating evictions honoring Pod Disruption Budgets etc Once Evictor makes a node empty it s deleted automatically Cloud vendor supportAt the moment Karpenter only supports AWS The code has a lot of AWS specific hardcoded logic For instance using EC Fleet and Spot Fleet without a way forward for other clouds Karpenter has fake interfaces created in the code so the project looks pluggable and open enough if someone were to take the initiative to enable other cloud support in Karpenter CAST AI supports AWS EKS kOps Google Cloud Platform GKE and Microsoft Azure AKS No node poolsThe promise of being free of node pools sounds great But Karpenter doesn t offer users almost any control over the scheduling decisions when using a “naked Provisioner  A Provisioner is Karpenter s Kubernetes CRD which defines the node creation constraints For example if you had workloads that needed a GPU and you wanted the GPU nodes to have a taint so that only the pods that actually need it are placed on those nodes you would create a Provisioner like that apiVersion karpenter sh valphakind Provisionermetadata name gpuspec requirements key node kubernetes io instance type operator In values pxlarge pxlarge pxlarge taints key nvidia com gpu value true effect “NoSchedule In Karpenter the engineer still needs to have deep knowledge of the available instance types with all of their nuances  To use the SSDs in a Ks cluster you would need to create a user data script that makes a single logical disk out of those local SSDs and creates a symbolic link for the kubelet to use That requires creating an EC Launch Template and referencing it in the Provisioner resource And most importantly you need to keep it up to date if you want to achieve cost savings Conclusion In more complicated clusters you d have to create many different Provisioners i e node pools one for GPUs another one for storage optimized yet another one for infrequently interrupted Spot instances etc Provisioner conflictsWhen there are multiple Provisioner resources defined and an unschedulable pod can tolerate select any of them the result will be non deterministic  Here s an example apiVersion karpenter sh valphakind Provisionermetadata name team aspec labels team a requirements key node kubernetes io instance type operator In values m large apiVersion karpenter sh valphakind Provisionermetadata name team bspec labels team b requirements key node kubernetes io instance type operator In values mxlarge apiVersion vkind Podmetadata name podspec containers image nginx name podThe nginx pod would be scheduled on either the m large or the mxlarge node chosen based on the sequence the API Server returns for the records This is another dimension that the DevOps engineer would need to think about  The Provisioners should clearly define constraints and all pods should clearly define the selectors to reduce or eliminate randomness  In CAST AI the selectors tolerations are predefined and engineers don t have to come up with them on their own Pod grouping a k a Bin Packing on provisioning Karpenter s GitHub states that they use bin packing but only in the nodePlacer sense That is grouping pods to be placed on nodes to avoid creating a separate node for each pod  In CAST AI we use Permutations and Clique functions Their purpose is to find out the most optimal pod groupings  Karpenter doesn t have elaborate algorithms to group pods optimally The algorithm used is basically creating a hash of the pod constraints This means that otherwise compatible pods will end up on different nodes Karpenter will create multiple nodes  Consider this example apiVersion vkind Podmetadata name podspec nodeSelector topology kubernetes io zone eu central a containers image nginx name pod apiVersion vkind Podmetadata name podspec affinity nodeAffinity requiredDuringSchedulingIgnoredDuringExecution nodeSelectorTerms matchExpressions key topology kubernetes io zone operator In values eu central a eu central b containers image nginx name podEven though the pods could fit into a single node placed in the eu central a zone Karpenter will create two nodes that might even end up in the same zone because the hash of the pod constraints is different Your Cluster has overprovisioned capacity and Karpenter leaves you without a way to shrink it Cost optimizationWhen Karpenter bin packs pods it produces a list of viable instance types per each pod group For example if there s a pod group that needs CPU and GiB then a list of all instance types that have at least CPU and GiB is retrieved The list is sorted by resource weight Karpenter sorts those instance types using a weight function where CPU GiB favoring nodes with higher CPU and lower memory weightOf uses a euclidean distance function to compare the instance types Units are normalized such that cpu gb mem Additionally accelerators carry an arbitrarily large weight such that they will dominate the priority but if equal will still fall back to the weight of other dimensions func weightOf instanceType cloudprovider InstanceType float return euclidean float instanceType CPU Value float instanceType Memory ScaledValue resource Giga gb cpu float instanceType NvidiaGPUs Value Heavily weigh gpus x float instanceType AMDGPUs Value Heavily weigh gpus x float instanceType AWSNeurons Value Heavily weigh neurons x After sorting only the first of the nodes are picked This list might not contain the cheapest instance types because of Karpenter s particular weighing system There is no inventory database that can tell exactly how much something costs After the bin packing and sorting the list is passed to the EC Fleet API The mode of choosing the instance type depends on whether it s an on demand node or spot instance On demand instancesIn this case Karpenter passes the “lowest cost allocation method that makes the EC Fleet API choose the cheapest instance type out of the received viable instance types There might be cheaper instance types but the API works with what it was given Spot instancesKarpenter passes the “capacity optimized prioritized allocation method that makes the EC Fleet API choose the instance types which have the highest availability prioritizing the instance types at the top of the list This has nothing to do with cost optimization and could be considered something similar to the CAST AI “Least interrupted Spot reliability setting CAST AI offers an entirely different approach to cost optimization The platform selects the most cost efficient instances that match the workload requirements and automatically rightsizes instances to avoid overallocation CAST AI also comes with features such as cost reporting on any level information about cluster cost or potential savings Karpenter doesn t have any of those Karpenter vs CAST AI which autoscaler is a better pick for you As you can see Karpenter offers a limited set of functionalities right now AWS Karpenter is an option if you re on AWS and considering the native Kubernetes Cluster Autoscaler Today AWS offers instances so node pools on which the Kubernetes Cluster Autoscaler works become unmanageable considering the exhaustible instance inventory This is essentially what Karpenter kind of tries to solve If you re looking for an autoscaler that can significantly reduce your cloud bill for production workloads without impacting their availability you need to look elsewhere CAST AI offers a substantially more robust set of features which makes it a great fit for reliable automated cost reduction on production and development workloads It also works with all three major cloud providers AWS Google Cloud and Azure To see what results could CAST AI bring you you can register and start with a free cluster analysis or book a quick demo by clicking the button below 2021-12-10 10:53:34
海外TECH DEV Community Top 5 WordPress Trends for 2022 https://dev.to/appdevelopaustralia/top-5-wordpress-trends-for-2022-49li Top WordPress Trends for WordPress is an open source content management system that also happens to be one of the favourites when it comes to developing a website It is used by bloggers as well as businesses to set up informative websites highly customised websites as well as ecommerce websites The major advantage of WordPress is that it has a low learning curve but it is always beneficial to hire WordPress developers This article provides more information on the top trends for WordPress development in Top WordPress Development TrendsIt is a good decision to opt for WordPress to develop your website However it is a good practice to follow the latest design amp development trends when considering WordPress development in Sydney Here are the top development trends 2021-12-10 10:46:24
海外TECH DEV Community Build Chatbot for Website using Chatwoot! https://dev.to/aviyel/build-chatbot-for-website-using-chatwoot-4980 Build Chatbot for Website using Chatwoot That moment when your internet is down and you are frustrated with late responses of a representative of your broadband company going through their CRMs Do you want your customers to feel the same If not Chatbots are the solution and how do you integrate chatbots into your application Umm well why worry when Aviyel comes with another valuable event where you will learn how to integrate chatbots into your website using Chatwoot Chatbots are here to make our life easier Chatbot helps massively in better customer engagement which is the prime goal for most companies With the help of chatbots we can improve our lead generation If you want to improve your customer engagement improve your lead generation this event is the solution Join this event and learn how to build Chatbot for a website using Chatwoot with Murtuzaali Surti Why should one join this event You will learn what are chatbots and their impact on customer experience Learn why one should prefer chatwoot for integrating chatbots into their websites You will take a hands on approach to various chatwoot features which will help in improving your customer engagement Murtuzaali Surti is coming live on Aviyel where he will help you guys by building chatbots for websites using Chatwoot Murtuza is a front end web developer and also an author at CSS Tricks He is good at designing accessible responsive and elegant user interfaces Murtuza is also having the ability to write in depth articles regarding web development and UI design Join us to get hands on experience with Chatwoot amp open source Date December th Time AM PST AM ESTRegister here Impressed Check out the rest of our events Let s build open source together Team AviyelMurtuzaali Surti Socials Twitter Murtuzaali SurtiGitHub Murtuzaali SurtiHashnode Murtuza s BlogLinkedIn Murtuzaali Surti 2021-12-10 10:34:31
海外TECH DEV Community My Django-Svelte setup for fullstack development https://dev.to/besil/my-django-svelte-setup-for-fullstack-development-3an8 My Django Svelte setup for fullstack development My Django Svelte workflow for fullstack developmentMotivationAbout this postThe appPrerequisitesSetupCode Django settings pyCode SvelteCode Django spa viewTest itAdding AuthenticationRest APIBuilding for ProductionConclusions Motivation I recently discovered Svelte and became my first choice for personal projects and MVP POCs As a backend developer I struggled a lot with frameworks like React or Vue looking for a productive workflow Svelte is dead simple compared to them in my opinion And yet very powerful However coming from Django I still struggled on stuff like security or form validation if I want a SPA do I really need to use only Django Rest Framework and implement everything through REST API Take authentication for example Django has built in views for doing it in a secure way Do I really need to re implement it every time client side using JWT Looks like a waste of time for my productivity at least I really like Django approach “batteries included since it ships with best practices and it makes me a lot more focused on the goal I want to achieve On the other hand I still want the flexibility and reactivity provided by a SPA framework So after multiple projects I d like to share in this blog post my personal take aways and show how I scaffold my projects in order to get a Django website using the powerful template system for authentication registration and password recovery using Django built in views a Svelte app served by Django with hot reloading during developmentsome Rest API to provide data to the SPA app using the awesome Django REST FrameworkThis way helps me a lot because it keeps the best of the three worlds without compromising productivity About this post Please consider the following as my personal vademecum for setting up a Django Svelte project quickly with basic usefules dependencies such as whitenoise black and authentication which I haven t found much covered online It is a concentrated boilerplate of my favourites tweaks on Django that made me proficient Feel free to ignore those who don t interests you Any feedback is very welcome I m using Svelte because is my favourite but the approach should work for Vue and React with obvious adjustments A medium Django Python and Svelte knowledge is required The app Prerequisites My tools for the job are poetrynpm Setup My setup is very similar to the one in the DRF quickstart but I prefer poetry to pipmkdir django svelte sample appcd django svelte sample app Django setupFor poetry init go for the defaults and add the basic dependencies for our Django project afterpoetry initpoetry add django whitenoisepoetry add dev black allow prereleasesSet Django up note the final dot poetry run django admin startproject myapp Svelte setupnpx degit sveltejs template frontendcd frontendnpm installcd SetupYou should have the following structure find frontend frontend README md frontend rollup config js frontend public frontend public index html frontend public global css frontend public favicon png frontend gitignore frontend package lock json frontend package json frontend scripts frontend scripts setupTypeScript js frontend src frontend src App svelte frontend src main js pyproject toml myapp myapp asgi py myapp init py myapp settings py myapp urls py myapp wsgi py manage py poetry lock venv frontend node modules Code Django settings py We will configure some settings for Django in order to enable Django Debug using Environment Variablesconfigure loggingread templates from a root folder instead of subapps templates managing static files with WhitenoiseWe will modify the myapp settings py file Introducing DJANGO DEBUGThis is very useful when working with Docker or Heroku and you want to dinamically turn on off the Django debug mode ReplaceDEBUG Truewithimport osDEBUG DJANGO DEBUG in os environ and os environ DJANGO DEBUG ON Configure loggingI usually configure logging as the following logging level INFO if LOGGING LEVEL not in os environ else os environ LOGGING LEVEL LOGGING version disable existing loggers False formatters console format asctime s levelname s name s lineno s message s handlers console class logging StreamHandler formatter console root handlers console level WARNING propagate False loggers django server level WARNING handlers console propagate False myapp level logging level handlers console propagate False You can now easily change the log level using the LOGGING LEVEL env variable Feel free to change the format as you prefer Django Template folderI generally prefer to have all my html templates inside a root level templates folder instead of every app having appname templates appname folder Modify the TEMPLATES variable from TEMPLATES BACKEND django template backends django DjangoTemplates DIRS APP DIRS True OPTIONS context processors django template context processors debug django template context processors request django contrib auth context processors auth django contrib messages context processors messages toTEMPLATES BACKEND django template backends django DjangoTemplates DIRS myapp templates lt here and create the folder mkdir p myapp templates Django static filesAs mentioned I really love Whitenoise for serving static files directly from Django This helps me a lot during development and deploying because I can stay within Django We now create a staticfiles folder inside myapp where files will be collected when we go to production and the folder that will contain the compiled Svelte files that will be served as Django static files we will see it later mkdir p myapp static frontendWe need to configure out static configurations accordingly STATIC ROOT os path join BASE DIR myapp staticfiles STATIC URL static STATICFILES STORAGE whitenoise storage CompressedManifestStaticFilesStorage STATICFILES DIRS os path join BASE DIR myapp static And do not forget to add Whitenoise to the list of middlewares MIDDLEWARE django middleware security SecurityMiddleware whitenoise middleware WhiteNoiseMiddleware lt here django contrib sessions middleware SessionMiddleware django middleware common CommonMiddleware Finish Django configurationLet s complete Django configuration creating applying the migrations and starting up the server just to be sure no warnings came upIf you want to just check that everything is ok you can run DJANGO DEBUG ON poetry run python manage py makemigrationsDJANGO DEBUG ON poetry run python manage py migrateDJANGO DEBUG ON poetry run python manage py runserverYou should seeWatching for file changes with StatReloader INFO django utils aut Watching for file changes with StatReloaderPerforming system checks System check identified no issues silenced December Django version using settings myapp settings Starting development server at Quit the server with CONTROL C So far so good We just instructed Django to do some useful stuff through standard configuration Let s add the Svelte part in order to see something Code Svelte For now we will just expose the Svelte default app from Django The idea here is we will serve the files from Django static frontend dir and we will develop from Django ie localhost instead of localhost default rollup dev server All we have to do is configure rollup to emit the build files in the static django folder Go to frontend rollup config js and change the export default like this export default input src main js output sourcemap true format iife name app file myapp static frontend bundle js lt here plugins production amp amp livereload myapp static frontend lt here Move the frontend public files to djangomv frontend public favicon png myapp static frontend mv frontend public global css myapp static frontend Now in a terminal starts rollup dev servercd frontendnpm run devAnd you will see the bundle files created under the Django folder ls myapp static frontendbundle css bundle js bundle js map favicon png global css index htmlWe will leave the rollup dev server up so that we will have the hot reload while working on the Django side so leave the server up and change terminal In order to serve it from Django we need to render the template using a standard view Code Django the SPA view We now create a dedicated Django app that will just render the Svelte appcd myapppoetry run django admin startapp spacd mkdir p myapp templates spamv frontend public index html myapp templates spa Replace the content of myapp spa views py with the following from django views generic import TemplateViewclass SpaView TemplateView template name spa index html Modify the myapp templates spa index html using static resources from the frontend load static lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset utf gt lt meta name viewport content width device width initial scale gt lt title gt Svelte app lt title gt lt link rel icon type image png href static frontend favicon png gt lt lt here gt lt link rel stylesheet href static frontend global css gt lt lt here gt lt link rel stylesheet href static frontend bundle css gt lt lt here gt lt script defer src static frontend bundle js gt lt script gt lt lt here gt lt head gt lt body gt lt body gt lt html gt Add the view in the myapps urls py myapps urls pyfrom django contrib import adminfrom django urls import pathfrom myapp spa views import SpaView lt hereurlpatterns path admin admin site urls path SpaView as view name spa lt here and finally in order to add it in the installed apps we need to modify myapp spa apps pyclass SpaConfig AppConfig default auto field django db models BigAutoField name myapp spa lt hereadd myapp spa in the INSTALLED APPS in myapp settings pyINSTALLED APPS django contrib admin django contrib auth django contrib staticfiles myapp spa lt here Test it From the root folder of the project ie the one with the frontend and myapp folders inside run in two different terminal windows st shell sveltecd frontendnpm run dev nd shell djangoDJANGO DEBUG ON poetry run python manage py runserverGo to localhost and you will see the Svelte app served directly from Django Try changing frontend src App svelte or frontend src main js hit Ctrl R and you will see it hot reloaded from Django Remember to disable cache or force the browser to refresh the page if you don t see any change Don t forget that you need the npm run dev in background in order to keep sync the bundle files under Django static folder Secure our SPA the Django way Now we can leverage the standard Django features such as authentication First secure our View extending the LoginRequiredMixin In myapp spa views pyfrom django views generic import TemplateViewfrom django contrib auth mixins import LoginRequiredMixinclass SpaView LoginRequiredMixin TemplateView template name spa index html To enable auth add in your myapp settings pyfrom django urls import reverse lazyLOGIN URL reverse lazy login LOGIN REDIRECT URL reverse lazy spa LOGOUT REDIRECT URL reverse lazy spa and in myapps urls pyfrom django contrib import adminfrom django urls import path include lt herefrom myapp spa views import SpaViewurlpatterns path admin admin site urls path accounts include django contrib auth urls lt here path SpaView as view name spa Create the login form template mkdir p myapp templates registrationtouch myapp templates registration login htmlAdd the following to myapp templates registration login html taken from the django documentation lt html gt lt head gt lt head gt lt body gt if form errors lt p gt Your username and password didn t match Please try again lt p gt endif if next if user is authenticated lt p gt Your account doesn t have access to this page To proceed please login with an account that has access lt p gt else lt p gt Please login to see this page lt p gt endif endif lt form method post action url login gt csrf token lt table gt lt tr gt lt td gt form username label tag lt td gt lt td gt form username lt td gt lt tr gt lt tr gt lt td gt form password label tag lt td gt lt td gt form password lt td gt lt tr gt lt table gt lt input type submit value login gt lt input type hidden name next value next gt lt form gt Assumes you set up the password reset view in your URLconf lt p gt lt a href url password reset gt Lost password lt a gt lt p gt lt body gt lt html gt Create a super user running in a terminalpoetry run python manage py createsuperuserNow if you try to hit localhost you will be redirected to http localhost accounts login next Try to login with the provided credentials and you will see the Svelte app again Hit localhost accounts logout to logout Rest API Now we will add a very simple REST API using Django Rest Framework and consume it from the Svelte App Note that our Svelte SPA app will leverage DRF SessionAuthentication since it will invoke the API in the same context of the Django app This is the most secure way in my opinionFirst install DRFpoetry add djangorestframeworkIn addition since Django has just been released we need to install pytz since DRF still uses itpoetry add pytzand add it in myapp settings py INSTALLED APPSINSTALLED APPS django contrib admin django contrib auth django contrib contenttypes django contrib sessions django contrib messages django contrib staticfiles rest framework lt here myapp spa Create a new Django app for the APIcd myapppoetry run django admin startapp apicd Add the mock api in myapp api views pyfrom rest framework views import APIViewfrom rest framework response import Responsefrom rest framework import authentication permissionsfrom rest framework renderers import JSONRendererclass GreetingApi APIView authentication classes authentication SessionAuthentication permission classes permissions IsAuthenticated renderer classes JSONRenderer def get self request format None return Response message Hello world Note that we are using the default Django Session Authentication via login form the API is available only for authenticated usersNow adjust frontend src App svelte lt script gt import onMount from svelte export let name let apimessage Waiting for server onMount async gt let resp await fetch api greet then res gt res json console log resp apimessage JSON stringify resp lt script gt lt main gt lt h gt Hello name lt h gt lt p gt Visit the lt a href gt Svelte tutorial lt a gt to learn how to build Svelte apps lt p gt lt h gt Data from server lt h gt apimessage lt main gt Add the API to myapp urls pyfrom django contrib import adminfrom django urls import path includefrom myapp spa views import SpaViewfrom myapp api views import GreetingApi lt hereurlpatterns path admin admin site urls path accounts include django contrib auth urls path api greet GreetingApi as view lt here path SpaView as view name spa Hit localhost login and enjoy your Django based SPA using Server Side Authentication and Rest API Building for Production In order to make our app ready to Production we need Gunicorn installedpoetry add gunicorncollect all static filespoetry run python manage py collectstaticconfigure the allowed hosts myapp settings py change ALLOWED HOSTS toALLOWED HOSTS localhost Now you are ready to runpoetry run gunicorn myapp wsgiGo to localhost and enjoy your gunicorn served app Conclusions In this quite long walkthrough we saw different things set up a Django app with my personal useful tweaksset up an integrated Svelte app served by Djangoconfigure Django built in authentication to secure our SPAproviding some Rest API for the SPA to consumepacking everything up for ProductionYou can find all the code here on github I hope this post can help you make your life as developer easier I m going to add other posts integrating Docker Docker compose and some utility scripts for local development Feel free to comment I d be glad to receive any feedback your have 2021-12-10 10:22:55
海外TECH DEV Community How angular starts https://dev.to/sibaspage/how-angular-starts-519j How angular startsHow angular starts executing There is file name called angular json which act like a configuration for the whole application Its looks like this build builder angular devkit build angular browser options outputPath dist angular starter index src index html main src main ts polyfills src polyfills ts tsConfig tsconfig app json aot false assets src favicon ico src assets styles node modules angular material prebuilt themes deeppurple amber css src style css The entry point will be mentioned in the main section Which is main ts here The main ts file creates a browser environment to run the app import platformBrowserDynamic from angular platform browser dynamic Along with this it called a function called bootstrapModule platformBrowserDynamic bootstrapModule AppModule In the above code AppModule is getting bootstrapped AppModule is looks like thisimport BrowserModule from angular platform browser import NgModule from angular core import AppComponent from app component NgModule declarations AppComponent imports BrowserModule providers entryComponents bootstrap AppComponent export class AppModule If you see in the AppModule AppComponent is getting bootstrapped The AppComponent is defined in app component ts file Which looks like belowimport Component from angular core Component selector app root templateUrl app component html styleUrls app component css export class AppComponent title angular These file interacts with the webpage and serves data to it After this its calls index html which looks like this lt doctype html gt lt html lang en gt lt head gt lt meta charset utf gt lt title gt Angular lt title gt lt base href gt lt meta name viewport content width device width initial scale gt lt head gt lt body gt lt app root gt lt app root gt lt body gt lt html gt The html template of the root component is displayed inside the lt app root gt lt app root gt 2021-12-10 10:07:38
Apple AppleInsider - Frontpage News Best apps for managing To Do lists on your iPhone and iPad https://appleinsider.com/articles/21/12/09/best-apps-for-managing-to-do-lists-on-your-iphone-and-ipad?utm_medium=rss Best apps for managing To Do lists on your iPhone and iPadThe iPhone is the single best place for a To Do list because you are nearly always close to it Here are the best task management apps for it or your iPad Just as with calendars and email and weather apps you already have a To Do app on your iPhone Apple s own Reminders app is typical of the company in that it s quite clearly simple to use quite obviously free but it also hides how powerful it can be Reminders is really a kind of mid level To Do app There are ones that are much more basic there are others that are mid range And then there are just a couple that are so powerful that they can handle anything you need to throw at them anything you need to stay on top of Read more 2021-12-10 10:01:48
医療系 医療介護 CBnews オミクロン株、3空港到着の乗客から8例確認-厚労省が発表、医療機関で隔離 https://www.cbnews.jp/news/entry/20211210194431 医療機関 2021-12-10 19:55:00
医療系 医療介護 CBnews 地ケアの転棟患者割合、400床未満も減算適用を-支払側主張、機能に応じた評価のめりはりも https://www.cbnews.jp/news/entry/20211210185203 中央社会保険医療協議会 2021-12-10 19:20:00
金融 JPX マーケットニュース [東証]監理銘柄(確認中)の指定:(株)鴨川グランドホテル https://www.jpx.co.jp/news/1023/20211210-12.html 鴨川グランドホテル 2021-12-10 19:25:00
ニュース BBC News - Home Julian Assange can be extradited to the US, court rules https://www.bbc.co.uk/news/uk-59608641?at_medium=RSS&at_campaign=KARANGA assange 2021-12-10 10:54:47
ニュース BBC News - Home Boris Johnson's press chief Jack Doyle spoke at No 10 party last year https://www.bbc.co.uk/news/uk-politics-59601447?at_medium=RSS&at_campaign=KARANGA december 2021-12-10 10:36:33
ニュース BBC News - Home Cambo oil field development off Shetland to be paused https://www.bbc.co.uk/news/uk-scotland-59608521?at_medium=RSS&at_campaign=KARANGA shell 2021-12-10 10:54:16
ニュース BBC News - Home Verstappen fastest in first practice, with Hamilton third https://www.bbc.co.uk/sport/formula1/59608234?at_medium=RSS&at_campaign=KARANGA dhabi 2021-12-10 10:40:59
ニュース BBC News - Home England fightback 'vitally important' for Ashes series - Malan https://www.bbc.co.uk/sport/cricket/59606955?at_medium=RSS&at_campaign=KARANGA England fightback x vitally important x for Ashes series MalanEngland s second innings fightback in the first Ashes Test was vitally important to show they can compete in the five match series says Dawid Malan 2021-12-10 10:15:00
ビジネス 不景気.com ブリヂストンが防振ゴム・化成品事業を譲渡、売却損1190億円 - 不景気.com https://www.fukeiki.com/2021/12/bridgestone-sellout-v-rubber.html 防振 2021-12-10 10:14:11
北海道 北海道新聞 石原内閣官房参与が辞任へ 助成金受給、就任1週間 https://www.hokkaido-np.co.jp/article/621568/ 内閣官房参与 2021-12-10 19:10:00
北海道 北海道新聞 首相、台湾TPP申請歓迎 「重要な経済パートナー」 https://www.hokkaido-np.co.jp/article/621572/ 参院本会議 2021-12-10 19:15:00
北海道 北海道新聞 交通職場「カスハラ」46% 物流も、2万人調査 https://www.hokkaido-np.co.jp/article/621556/ 労働組合 2021-12-10 19:00:48
北海道 北海道新聞 能と現代サーカスの競演 香川、高松城跡 https://www.hokkaido-np.co.jp/article/621550/ 高松 2021-12-10 19:00:48
北海道 北海道新聞 道東沖の海底で「ホシムシ」大量死 赤潮の影響? 死骸が網に付着し、漁業の妨げに https://www.hokkaido-np.co.jp/article/621547/ 無脊椎動物 2021-12-10 19:15:04
北海道 北海道新聞 11月末のサンマ水揚げ量 道内は過去最低の前年比2%増 全国は34%減で3年連続で過去最低更新が決定的に https://www.hokkaido-np.co.jp/article/621567/ 漁業協同組合 2021-12-10 19:09:00
北海道 北海道新聞 日大、田中前理事長と「決別」 背任舞台の関連会社を清算 https://www.hokkaido-np.co.jp/article/621566/ 所得税法 2021-12-10 19:07:00
北海道 北海道新聞 道南感染ゼロ 新型コロナ https://www.hokkaido-np.co.jp/article/621565/ 道南 2021-12-10 19:06:00
北海道 北海道新聞 SBI、新生銀へのTOB成立 株保有比率、48%近辺に上昇 https://www.hokkaido-np.co.jp/article/621564/ 新生銀行 2021-12-10 19:04:00
北海道 北海道新聞 帰還願うイルミネーション 全町避難の福島・双葉 https://www.hokkaido-np.co.jp/article/621563/ 原発事故 2021-12-10 19:04:00
北海道 北海道新聞 楽天、川島を獲得 ソフトバンクから自由契約 https://www.hokkaido-np.co.jp/article/621553/ 川島慶三 2021-12-10 19:02:04
IT 週刊アスキー スマホ版ワクチン接種証明書を発行へ、申請にはマイナンバーカードが必要 https://weekly.ascii.jp/elem/000/004/077/4077735/ 生年月日 2021-12-10 19:30:00
IT 週刊アスキー 「ペルソナ」の対戦格闘『P4U2』がAC版Ver.2.50にバージョンアップした“リマスター版”として登場! https://weekly.ascii.jp/elem/000/004/077/4077739/ nintendoswitchpcsteam 2021-12-10 19:10:00

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)